def memoize
cache = {}
lambda { |*args|
unless cache.has_key?(args)
cache[args] = self[*args]
end
cache [args]
}
end
factorial = lambda {|x| return 1 if x== 0; x*factorial[x-1];}.memoize
puts factorial.call 10
The code is from book "The ruby programming language ". But it confuse me : how can the method(memoize) apply to a lambda as its method? Can lambda followed by other lambda with dot(.) as its own method?
lambda {|x| return 1 if x== 0; x*factorial[x-1];}.memoize
BTW: The above code works in irb, but ruby interpreter encounter error as following:
memoize.rb:11: private method `memoize' called for #<Proc:0x0000000103bba018@memoize.rb:11> (NoMethodError)
Why?