« Return to Thread: Defining a function inside a function. Whats this feature ? How to use inside a class ?

Re: Defining a function inside a function. Whats this feature ? How to use inside a class ?

by botp :: Rate this Message:

Reply to Author | View in Thread

On Jan 8, 2008 10:06 PM, Sur <sur.max@...> wrote:

> No, I was not actually saying that... In the class I meant this...
> class Person
>   def man
>     def author
>        p "I am author"
>     end
>   end
> end
>
> and if I call Person.new.man.author, it gives NoMethodError.

you assume that it's a hierarchy, but it's not.

irb(main):009:0> Person.new.man
=> nil
irb(main):010:0> Person.new.man.author
NoMethodError: undefined method `author' for nil:NilClass
        from (irb):10
        from :0
irb(main):011:0> Person.new.author
"I am author"
=> nil

the chain seems to work on plain defs since by default if you do not
specify a class, ruby creates it in Object class.  Thus the methods
defined are Object methods, ergo they become "public" so to speak.
Thus even nil class acquired the reader/author method; thus exhibiting
the seemingly hierachical behaviour (see my prev post). There is no
function as function per se in ruby. There are only  methods wc of
course belong to a class.

kind regards -botp

 « Return to Thread: Defining a function inside a function. Whats this feature ? How to use inside a class ?