Hello,
I am curious, is there a way to find out an object type?
TIA,
Phy
Hello,
I am curious, is there a way to find out an object type?
TIA,
Phy
object.kind_of?( Array ) #=> To test if it is something
object.is_a?( Array ) #=> Same
object.class #=> Tells you what class the object thinks it is.
On Feb 19, 2007, at 11:38 PM, Phy P. wrote:
I am curious, is there a way to find out an object type?
You can find out what class gave ‘birth’ to the object via #class:
[1,2].class # Array
3.class # Fixnum
Note that #class does not return a string (e.g., “Array”) but instead
returns a reference to the actual class object:
a = [1,2].class.new # allocates a brand new array
p a # []
It is important to realize that the ‘class’ of an object is really just
a hint at how an object will respond to methods. It might be a really
good hint, but a hint nevertheless since objects are free to override
method definitions provided by the class or even to add methods that
the class doesn’t provide:
b = [10,20,30]
def b.penultimate
self[-2]
end
b.penultimate # 20
Gary W.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs