Re: How to find out object type

ah, thats better. So now for the real nubie question, I am lost as to
why this does not work:

irb(main):001:0> o = 123
=> 123
irb(main):002:0> #{o} = Array.new
irb(main):003:0* o.class
=> Fixnum
irb(main):004:0> #{o}.class
irb(main):005:0*
irb(main):006:0* ^C
irb(main):006:0>

I was hoping to be create an array from the numb stored as “o”, but this
must be wrong, because trying to get the class of the object does not
work. Any help?

----- Original Message ----
From: Gary W. [email protected]
To: ruby-talk ML [email protected]
Sent: Monday, February 19, 2007 8:51:18 PM
Subject: Re: How to find out object type

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.

On 2/20/07, Phy P. [email protected] wrote:

irb(main):006:0>

I was hoping to be create an array from the numb stored as “o”, but this must be wrong,
because trying to get the class of the object does not work. Any help?

irb(main):001:0> o = 42
=> 42
irb(main):002:0> the_o_array = [o]
=> [42]
irb(main):003:0> the_o_array.class
=> Array

hth,
-Harold

On Feb 20, 2007, at 12:01 AM, Phy P. wrote:

ah, thats better. So now for the real nubie question, I am lost as
to why this does not work:

irb(main):001:0> o = 123
=> 123
irb(main):002:0> #{o} = Array.new
irb(main):003:0* o.class
=> Fixnum
irb(main):004:0> #{o}.class

The #{} notation is only applicable inside a string: “#{o}”. The
way you are using it make the line look like a comment.
Everything after the # is simply discarded.

Maybe you are looking for something like:

a = 123
b = [o]
p b # [123]

Gary W.