logo       

Re: Interesting behaviour: msg#02380

ruby-talk

Subject: Re: Interesting behaviour

Deepak Gole wrote:
> def foo
> 1
> end
>
> foo ===>o/p 1
> foo.foo ===>o/p 1
> foo.foo.foo ===>o/p 1
> foo.foo.foo.foo.foo.foo.foo.foo.foo.foo.foo.foo.foo.foo.foo............foo
> ===>o/p 1
>
> I got above o/p

I see the same with ruby 1.8.6.

It looks like you have defined foo as a method in Object, and hence is
available to all objects:

>> def foo; 1; end
=> nil
>> "hello".foo
=> 1
>> Object.instance_methods.grep(/foo/)
=> ["foo"]

Ruby 1.9 makes this slightly better by making the method private:

$ irb19 --simple-prompt
>> "hello".foo
NoMethodError: undefined method `foo' for "hello":String
from (irb):1
from /usr/local/bin/irb19:12:in `<main>'
>> def foo; 1; end
=> nil
>> "hello".foo
NoMethodError: private method `foo' called for "hello":String
from (irb):3
from /usr/local/bin/irb19:12:in `<main>'
>> Object.private_instance_methods.grep(/foo/)
=> [:foo]

I'm not sure why irb doesn't define methods as singleton methods of the
'main' (top level) object. You can do this yourself with a bit of
fiddling:

>> class << self; self; end.class_eval { def bar; 2; end }
=> nil
>> bar
=> 2
>> 1.bar
NoMethodError: undefined method `bar' for 1:Fixnum
from (irb):4
from /usr/local/bin/irb19:12:in `<main>'
--
Posted via http://www.ruby-forum.com/.

Google Custom Search

News | Mail Home | sitemap | FAQ | advertise