How do I call a method that is a hash value?
call, hash, methods, ruby
Solution
that code doesn't work. it executes `a` at the time it is added to the hash, not when it is retrieved from the hash (try it in irb).
It doesn't work in the class because there is no `a` method defined on the class (you eventually define a method `a` on the instance.
Try actually using lambdas like
{0 => lambda { puts "hello world" }}
instead
Problem
Previously, I asked about a clever way to execute a method on a given condition "Ruby a clever way to execute a function on a condition." The solutions and response time was great, though, upon implementation, having a hash of lambdas gets ugly quite quickly. So I started experimenting. The following code works: ``` def a() puts "hello world" end some_hash = { 0 => a() } some_hash[0] ``` But if I wrap this in a class it stops working: ``` class A @a = { 0 => a()} def a() puts "hello world" end def b() @a[0] end end d = A.new() d.b() ``` I can't see why it should stop working, can anyone suggest how to make it work?