From: Sigurd Date: 2013-04-12T06:08:45+09:00 Subject: Re: confusion with Struct class Correct me if i'm wrong, but since when ruby 1.9 uses "name" for class name? I always though that it's Class.new.class.name or Class.class.name that gives proper result. I've looked at ruby source, and it looks that in ruby 1.9.3 it references module name, but the constant namespace have some side effect on it. On Apr 11, 2013, at 9:14 PM, Jesús Gabriel y Galán wrote: > On Thu, Apr 11, 2013 at 7:38 PM, Love U Ruby wrote: >> Here is another confusion: >> >> I tried the below code: >> >> =============================== >> Customer = Struct.new(:name, :address) do |x| >> def x.greeting >> "Hello #{name}!" >> end >> end >> >> p Customer.greeting #=> "Hello Customer!" >> =============================== >> >> Now my question is - How does instance variable has been assigned to >> `Customer`? > > The object x that is passed into the block is the class that is being > created by Struct. When you define x.greeting, this is a singleton > method on the class object, and when inside that method you call > "name", you are actually calling a method of the x object, which is > class. With this test, you have discovered that classes have a "name" > method, that contains the constant to which they are assigned (this is > done either when doing class X, or X = ): > > 1.9.2p290 :008 > Customer.methods > => [...:name,...] > > As you can see the class Customer has a name method. > > If you create a class without assigning it to a constant, it doesn't > have a name: > > 1.9.2p290 :009 > c = Class.new > => # > 1.9.2p290 :010 > c.name > => nil > > on the other hand: > > 1.9.2p290 :011 > C = Class.new > => C > 1.9.2p290 :012 > C.name > => "C" > > and > > 1.9.2p290 :013 > class D > 1.9.2p290 :014?> end > => nil > 1.9.2p290 :015 > D.name > => "D" > > Hope this helps, > > Jesus. >