6
2

More than 5 years have passed since last update.

rubyで整数チェック

Last updated at Posted at 2016-04-13

文字列に対して*.to_iをすると、数値の0に変換される。
これを利用して整数チェックを行う。

※コメントで指摘を受けました
文字列"1a"など、数値で始まるものは0ではなく先頭の数値に変換されます。

t = 1
puts t.to_i.to_s == t.to_s  # true
t = "1"
puts t.to_i.to_s == t.to_s  # true
t = "abc"
puts t.to_i.to_s == t.to_s  # false
t = "1a"
puts t.to_i.to_s == t.to_s  # false
6
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2