|
| <prev next> |
Re: Interesting behaviour: msg#02387ruby-talk
Pascal J. Bourguignon wrote: > Why? Ask youself why foo.foo.foo --> 1 in the irb console! > > Try: self.class > in both Scite and irb... It's not quite as simple as just looking at 'self', and it took me a long time to find out why. Ruby has a concept of a 'the current object' which is exposed using 'self', but there is also a more hidden concept of 'the current class' where method definitions go. I don't think there's an easy way to see the current class, but you can set it using class or class_eval. >> class Foo; end => nil >> Foo.instance_eval { p self } Foo => nil >> Foo.instance_eval { def bar; puts "bar"; end } => nil >> Foo.bar bar => nil >> Foo.new.bar NoMethodError: undefined method `bar' for #<Foo:0xb7c89710> from (irb):5 from :0 But: >> Foo.class_eval { p self } Foo => nil >> Foo.class_eval { def baz; puts "baz"; end } => nil >> Foo.baz NoMethodError: undefined method `baz' for Foo:Class from (irb):8 from :0 >> Foo.new.baz baz => nil So in both cases, self is the class Foo, but in the first case methods are defined in the singleton class of Foo, whilst in the second case they are defined as instance methods in the class Foo. -- Posted via http://www.ruby-forum.com/.
|
|
||||||||||||||||||||||||
|
|
|
| News | Mail Home | sitemap | FAQ | advertise |