确定字符串是否包含Ruby中的Integer或Float

use*_*647 1 ruby

假设我得到一些字符串输入,我想知道它是否包含一个Integer或一个Float.

例如:

input_1 = "100"
input_2 = "100.0123"
Run Code Online (Sandbox Code Playgroud)

现在,让我们考虑以下内容:

input_1.respond_to?(:to_f) # => true 
input_1.is_a?(Float)       # => false
input_1.is_a?(Fixnum)      # => false
input_1.to_f?              # => 100.0

input_2.respond_to?(:to_i) # => true
input_2.is_a?(Integer)     # => false
input_2.is_a?(Fixnum)      # => false
input_2.to_i               # => 100
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我们无法确定字符串是否包含a Integer或a Float.Ruby中是否有办法确定字符串是否包含a FixnumFloat

Max*_*Max 7

正确的方法是IntegerFloat方法.

Integer("100")
100
Integer("1.03")
# ArgumentError: invalid value for Integer(): "1.03"
Float("1.03")
1.03
Float("1.2e9")
1200000000.0
Float("100")
100.0
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方法制作方法:

class String
  def is_int?
    Integer(self) && true rescue false
  end

  def is_float?
    Float(self) && true rescue false
  end
end
Run Code Online (Sandbox Code Playgroud)