The function(s) defined within a function works fine with any hierarchy only within the main object but gives NoMethodError inside a class.
Lets exemplify it!
Here are the example of both main object and inside a class…
[source:ruby]
def person
def author
p “I am author”
end
def reader
p “I am reader”
end
def publisher
def authorized
p “I am a authorized publisher”
end
end
end
person.author # => I am author
person.reader # => I am reader
person.publisher.authorized # => I am authorized publisher
class Person
def publisher
def authorized
p “I am a authorized publisher”
end
end
end
Person.new.publisher.authorized # => NoMethodError
[/source]
Its an unexpected behavior in the main object. I don’t know whether its a bug or the feature. But as Matz says it will be removed in the future version of ruby, might be in 2.0
One Comment to "Defining function inside a function using def"
Please share your thoughts
Filed in: ruby


A common criticism I’ve heard from fans of Scheme and Javascript is that the pub2 method in the code below still has access to the hidden method.
It’s an interesting philosophical question. Ruby makes hidden available to Person, presumably because it’s a method of Person rather than a free-floating function, and so should be attached to Person and available anywhere inside that class. In Scheme, on the other hand, nested functions are genuinely hidden. The nearest equivalent in Ruby would probably require a local variable lambda for hidden.
class Person
def publisher
def hidden
%q[I am a hidden publisher]
end
hidden.gsub(/ hidden/, %q[])
end
def pub2
hidden
end
end
if (__FILE__ == $0)
p = Person.new
puts p.publisher
puts p.pub2
begin
puts p.publisher.hidden
rescue
puts %q[Could not access p.publisher.hidden]
end
end