Julian Leviston
2/6/2009 4:23:00 AM
Yeah, it's as if you opened the class and redefined two... you're right.
if you want to define the method only on the particular instance that
you run that one method on you can do something like this:
hope this helps.
Last login: Fri Feb 6 14:06:35 on ttys003
Phatty:~ julian$ irb
>> class Hi
>> def one
>> instance_eval("
def two
puts 'hi'
end
")
>> end
>> def two
>> puts 'woo'
>> end
>> end
=> nil
>> x = Hi.new
=> #<Hi:0x5eab78>
>> y = Hi.new
=> #<Hi:0x5e96b0>
>> x.two
woo
=> nil
>> y.two
woo
=> nil
>> x.one
=> nil
>> x.two
hi
=> nil
>> y.two
woo
=> nil
>>
On 06/02/2009, at 2:46 PM, Daly wrote:
> I'm doing this as a learning experiment. I would have thought that
> since self inside method one is an object, then two inside one would
> be defined on the object, not on the class.
>
> Phlip's explanation made it clear to me though. It's as if I opened
> the class and redefined two, correct?
>
> On Feb 5, 10:26 pm, Julian Leviston <jul...@coretech.net.au> wrote:
>> What happens when you call the one method is it redefines the two
>> INSTANCE METHOD at the class level (ie the context of instance method
>> definition in the class), which means ALL objects are affected.
>>
>> Why would you want to do this?
>>
>> Julian.
>>
>> On 06/02/2009, at 2:05 PM, Daly wrote:
>>
>>> Hello all,
>>
>>> If I have a class such as:
>>
>>> class Example
>>
>>> def one
>>> puts "one"
>>
>>> def two
>>> puts "two inside one"
>>> end
>>> end
>>
>>> def two
>>> puts "two inside Example"
>>> end
>>
>>> end
>>
>>> And I do:
>>> e = Example.new
>>> e.one
>>> e.two
>>
>>> I get, obviously:
>>> one
>>> two inside one
>>
>>> What I don't understand is that if after that I do:
>>> f = Example.new
>>> f.two
>>
>>> I still get:
>>> two inside one
>>
>>> Since the two method in question is defined within one, doesn't it
>>> behave like a method on the object e? How can it override the two
>>> method outside for the f object?
>>
>>> Thanks for your help in explaining this.
>>
>>
>