Re: Differences between irb and ruby.
by Minkoo Seo other posts by this author
Jun 30 2006 9:19PM messages near this date
Re: Differences between irb and ruby.
|
Re: Differences between irb and ruby.
Hi Ezra.
You've got it wrong. The point is that though a method that is defined
outside of any class becomes automatically part of Object, it can't be
called with exact receiver because the method is *private*.
In other words,
# foo is private method of Object
def foo
..
end
class Bar; end
# This is okay, because I'm calling self.foo and we do not
# need to state self as receiver.
foo
# This is completely wrong. Private method can't be called
# with exact receiver.
Bar.new.foo
Hope this helps.
Sincerely,
Minkoo Seo
On 7/1/06, Ezra Zygmuntowicz <ezmobius@[...].com> wrote:
>
>
> On Jun 30, 2006, at 7:10 PM, Minkoo Seo wrote:
>
> > Hi list.
> >
> > I've recently learned that irb and ruby (ruby interpreter) behave
> > differently often
> > and that irb is not running on ruby interpreter.
> >
> > As an example,
> >
> > [mkseo@uranus src]$ irb
> > irb(main):001:0> def foo
> > irb(main):002:1> puts "foo"
> > irb(main):003:1> end
> > => nil
> > irb(main):004:0> class Bar; end
> > => nil
> > irb(main):005:0> Bar.new.foo
> > foo
> > => nil
> > irb(main):006:0> quit
> >
> > irb let me call foo which is non-sense.
> >
> > [mkseo@uranus src]$ cat > test.rb
> > def foo
> > puts "foo"
> > end
> > class Bar; end
> > Bar.new.foo
> > [mkseo@uranus src]$ ruby test.rb
> > test.rb:5: private method `foo' called for #<Bar:0x2aaaaab00cc8>
> > (NoMethodError)
> > [mkseo@uranus src]$
> >
> > Ruby interpreter fails as expected.
> >
> > So, here's my question. Why is irb running on its own interpreter(or
> > simulator or whatever)?
> >
> >
> > Sincerely,
> > Minkoo Seo
>
>
> When you def a method in irb outside of any class definition it
> actually gets added to Object i believe. Since the top level of irb
> outside of any class definitions is essentially running inside of
> Object. So that is why you can call foo from inside of class Bar
> since class Bar inherits from Object by default.
>
> ez $ irb
> irb(main):001:0> self.class
> => Object
>
>
>
> -Ezra
>
>
>
>
Thread:
Minkoo Seo
Ezra Zygmuntowicz
Minkoo Seo
Ezra Zygmuntowicz
Austin Ziegler
Minkoo Seo
Logan Capaldo
Mauricio Fernandez
|