I decided to experiment with defining methods inside methods in Ruby and wrote this:
def foo
def bar
puts "hello"
end
bar
end
This defined, I ran foo and “hello” was printed as I expected. However I then tried foo.bar – which printed out “hello” twice. Why?
foo.barequalsfoo().bar()so you call firstfoowhich containsbarso it is executed once here, thenbaris executed one more time. At the endbaris called twice.What I don’t understand is this means the result of
foowhich isnilcan callbar.How is that possible ?
Edit: As explained in some answers, nested method are included in the class scope so weither bar is declared inside or outside foo does not make any difference.
Also Matz said that it may change from Ruby2.0
here is the example he wrote:
edit-Ruby2.0: It finally did not get implemented. So it remains the same.