Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind lambda to hash in Ruby?

Is it possible to implement in Ruby such behavior? (like JavaScript):

hash = {
  attr: 'value',
  lambda: -> do
    puts self[:attr]
    # puts @attr # or this way
  end
}

hash[:lambda].call #should print 'value'

Doesn't matter if it is patching or inheriting from Hash, as an accessing syntax itself. I just want make lambdas to access their parent hash without passing it on call.

like image 611
Urvalla Avatar asked Sep 05 '25 03:09

Urvalla


2 Answers

Instead of using self - call the hash by its variable name:

hash = {
  attr: 'value',
  lambda: -> do
    puts hash[:attr]
  end
}

hash[:lambda].call
# value
like image 176
Uri Agassi Avatar answered Sep 07 '25 19:09

Uri Agassi


Lambdas (or for that matter, any object) have no memory of hashes that they could be a value of.

They do however remember local variables. For example if you were to write

def make_lambda
  hash = {attr: 'value'}
  lambda do 
    hash[:attr]
  end
end

Then

make_lambda.call

Would return 'value' - even though hash is no longer in scope, the lambda remembers what was in scope when it was created (it's a closure)

like image 28
Frederick Cheung Avatar answered Sep 07 '25 19:09

Frederick Cheung