ruby 如何检查变量是数字还是字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8616360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:36:50  来源:igfitidea点击:

How to check if a variable is a number or a string?

ruby

提问by Leem.fin

How to check if a variable is a number or a string in Ruby?

如何在Ruby中检查变量是数字还是字符串?

回答by Michael Kohl

There are several ways:

有几种方式:

>> 1.class #=> Fixnum
>> "foo".class #=> String
>> 1.is_a? Numeric #=> true
>> "foo".is_a? String #=> true

回答by installero

class Object
  def is_number?
    to_f.to_s == to_s || to_i.to_s == to_s
  end
end

> 15.is_number?
=> true
> 15.0.is_number?
=> true
> '15'.is_number?
=> true
> '15.0'.is_number?
=> true
> 'String'.is_number?
=> false

回答by Christoph Geschwind

var.is_a? String

var.is_a? Numeric

回答by Frank Koehl

The finishing_movesgemincludes a String#numeric?method to accomplish this very task. The approach is the same as installero's answer, just packaged up.

finishing_moves宝石包括String#numeric?完成这项任务非常方法。方法和installero的回答一样,只是打包好了。

"1.2".numeric?
#=> true

"1.2e34".numeric?
#=> true

"1.2.3".numeric?
#=> false

"a".numeric?
#=> false

回答by BSalunke

Print its class, it will show you which type of variable is (e.g. String or Number).

打印它的类,它会告诉你是哪种类型的变量(例如字符串或数字)。

e.g.:

例如:

puts varName.class

回答by markhorrocks

class Object
  def numeric?
    Float(self) != nil rescue false
  end
end

回答by Liker777

if chr.to_i != 0
  puts "It is number,  yep"
end