确定 ruby 中对象的类型 [英] Determining type of an object in ruby
问题描述
我将使用 python 作为我正在寻找的示例(如果您不了解 Python,您可以将其视为伪代码):
<预><代码>>>>一 = 1>>>类型(一)<输入'int'>我知道在 ruby 中我可以做到:
1.9.3p194 :002 >1.班级=>固定编号
但这是确定对象类型的正确方法吗?
确定对象类型"的正确方法是调用 object.class代码>.
由于类可以从其他类继承,如果你想确定一个对象是否是特定类型的",你可以调用 object.is_a?(ClassName)
来查看 object
属于 ClassName
类型或派生自它.
通常类型检查不在 Ruby 中进行,而是根据对象响应特定方法的能力进行评估,通常称为鸭打字".换句话说,如果它响应你想要的方法,就没有理由去拘泥于类型.
例如,object.is_a?(String)
过于死板,因为另一个类可能会实现将其转换为字符串的方法,或者使其行为与 String 的行为方式相同.object.respond_to?(:to_s)
将是测试相关对象是否满足您的要求的更好方法.
I'll use python as an example of what I'm looking for (you can think of it as pseudocode if you don't know Python):
>>> a = 1
>>> type(a)
<type 'int'>
I know in ruby I can do :
1.9.3p194 :002 > 1.class
=> Fixnum
But is this the proper way to determine the type of the object?
The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object.class
.
Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.is_a?(ClassName)
to see if object
is of type ClassName
or derived from it.
Normally type checking is not done in Ruby, but instead objects are assessed based on their ability to respond to particular methods, commonly called "Duck typing". In other words, if it responds to the methods you want, there's no reason to be particular about the type.
For example, object.is_a?(String)
is too rigid since another class might implement methods that convert it into a string, or make it behave identically to how String behaves. object.respond_to?(:to_s)
would be a better way to test that the object in question does what you want.
这篇关于确定 ruby 中对象的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!