Two things come to mind, are you wanting class methods or instance
methods?
With the first one, class methods, you don’t have to create an instance
of
Person (I don’t think this is what you want) and you simply call the
methods
directly from the class
With the second, instance methods, you need to create an instance of the
Person using Person.new and then call the methods on the object.
#Class methods:
class Person
def Person.author
p “I am author”
end
def Person.reader
p “I am reader”
end
end
Person.author # -> I am author
Person.reader # -> I am reader
#Instance methods:
class Person
def author
p “I am author”
end
def reader
p “I am reader”
end
end
person = Person.new
person.author # -> I am author
person.reader # -> I am reader
In message “Re: Defining a function inside a function. Whats this
feature ? How to use inside a class ?”
on Tue, 8 Jan 2008 21:15:40 +0900, Sur [email protected] writes:
|I am not sure if I have seen it being used earlier or probably I don’t know
|how to use it.
|
|when I define function(s) inside a function within the main object, it
|works…
Don’t use def inside of def, in general. The behavior might be
changed in the future (2.0 or later).
Don’t use def inside of def, in general. The behavior might be
changed in the future (2.0 or later).
So, is it not the expected behavior of the “class” and we should not use
it
or its a bug that its allowing the def inside a def(specifically only in
main object) and will be fixed in the future release. Although I haven’t
read anywhere about Namespaced functions like classes and modules but I
was
just curious as it was an unexpected behavior to me.
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.