From: "Jesús Gabriel y Galán" Date: 2013-04-12T03:14:47+09:00 Subject: Re: confusion with Struct class 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.