LoginSignup
5
4

More than 5 years have passed since last update.

文字列が整数かどうか判断するメソッドを考えた

Posted at

ググっても納得のいく答えが見つからなったので・・・

引数に渡した文字列が整数に変換できるか判定する以下のようなメソッドを作りたい。

is_int?('1234') # true
is_int?('abcd') # false

案1

普通に正規表現を使う。

def is_int?(str)
  !str.match(/\D/)
end

案2

to_iの特性を利用して二重で変換した後に比較する。

def is_int?(str)
  str == str.to_i.to_s
end

どうするのがベストでしょうか。

5
4
6

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
5
4