I noticed some interesting use of ||= as below –
Code 1
array_1 ||= begin
(1..5).to_a.map {|el| el*10}
end
puts array_1.to_s # [10,20,30,40,50]
So I executed its following modified version –
Code 2
array_2 ||= def some_method
(1..5).to_a.map {|el| el*10}
end
puts array_2 # prints nothing
puts array_2.class # NilClass
puts some_method.to_s # [10,20,30,40,50]
- Why does
array_2gets initialised tonil? - Is it possible to invoke
some_methodusingarray_2object? how?
UPDATE
This is what I did for question 2
array_2 ||= "We've got #{def some_method;(1..5).to_a.map {|el| el*10};end;array_2.send(:some_method)}"
puts array_2 # We've got [10, 20, 30, 40, 50]
The return value of a method definition expression (
def) is implementation-defined. Most Ruby implementations simply returnnilfrom adefexpression, but Rubinius, for example, returns the compiled code of the method wrapped up in aCompiledMethodobject.