Urvalla
Urvalla

Reputation: 80

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.

Upvotes: 4

Views: 5874

Answers (2)

Uri Agassi
Uri Agassi

Reputation: 37409

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

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

hash[:lambda].call
# value

Upvotes: 8

Frederick Cheung
Frederick Cheung

Reputation: 84114

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)

Upvotes: 3

Related Questions