检查变量是否是 Ruby 中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7749416/
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
Check whether a variable is a string in Ruby
提问by davidchambers
Is there anything more idiomatic than the following?
有什么比以下更惯用的吗?
foo.class == String
回答by Candide
I think you are looking for instance_of?. is_a?and kind_of?will return true for instances from derived classes.
我想你正在寻找instance_of?。is_a?并将kind_of?为派生类的实例返回 true。
class X < String
end
foo = X.new
foo.is_a? String # true
foo.kind_of? String # true
foo.instance_of? String # false
foo.instance_of? X # true
回答by Andrew Grimm
A more duck-typing approach would be to say
一种更像鸭子的方法是说
foo.respond_to?(:to_str)
to_strindicates that an object's class may not be an actual descendant of the String, but the object itself is very much string-like (stringy?).
to_str表示对象的类可能不是 String 的实际后代,但对象本身非常类似于字符串(字符串?)。
回答by Federico Builes
You can do:
你可以做:
foo.instance_of?(String)
And the more general:
还有更一般的:
foo.kind_of?(String)
回答by Matthew
foo.instance_of? String
or
或者
foo.kind_of? String
if you you only care if it is derrived from Stringsomewhere up its inheritance chain
如果您只关心它是否源自String其继承链的某个地方
回答by steenslag
In addition to the other answers, Class defines the method === to test whether an object is an instance of that class.
除了其他答案之外,Class 还定义了方法 === 来测试对象是否是该类的实例。
- o.classclass of o.
- o.instance_of? cdetermines whether o.class == c
- o.is_a? cIs o an instance of c or any of it's subclasses?
- o.kind_of? csynonym for *is_a?*
- c === ofor a class or module, determine if *o.is_a? c* (String === "s"returns true)
- o.class类 o.
- o.instance_of?c确定是否o.class == c
- o.is_a?c是c的实例还是它的任何子类?
- o.kind_of?*is_a?* 的c同义词
- c === o对于类或模块,确定是否 *o.is_a? c* ( String === "s"返回真)
回答by schlegel11
I think a better way is to create some predicate methods. This will also save your "Single Point of Control".
我认为更好的方法是创建一些谓词方法。这也将保存您的“单点控制”。
class Object
def is_string?
false
end
end
class String
def is_string?
true
end
end
print "test".is_string? #=> true
print 1.is_string? #=> false
The more duck typing way ;)
更多鸭子打字方式;)

