LoginSignup
3
5

More than 5 years have passed since last update.

[ruby] 文字列から Integer や Float に変換できるか調べる

Last updated at Posted at 2014-11-27

文字列から Integer や Float に変換できるか調べる

to_ito_f だと無理やり変換して、Kernel#IntegerKernel#Float だと変換できないときに例外投げるんだよね

"5foo".to_i #=> 5
"foo5".to_i #=> 0

Integer "5foo" #~> invalid value for Integer(): "5foo" (ArgumentError)

文字列から Integer や float に変換できるか調べるためのメソッドをモンキーパッチ

class String
  def int_valid?
    Integer(self)
    true
  rescue ArgumentError
    false
  end

  def float_valid?
    Float(self)
    true
  rescue ArgumentError
    false
  end
end
3
5
0

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