Skip to content

Instantly share code, notes, and snippets.

@vasilakisfil
Last active April 13, 2016 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasilakisfil/e095e5ea133e23374b723fe14063725d to your computer and use it in GitHub Desktop.
Save vasilakisfil/e095e5ea133e23374b723fe14063725d to your computer and use it in GitHub Desktop.
Having fun with instance_exec in Ruby
class Hash
def reshape(binding)
new_hash = self.clone
new_hash.each{|k, v| new_hash[k] = (binding.instance_exec(&(v))) if v.is_a? Proc}
return new_hash
end
end
def foo_method
10
end
@foo_variable = 20
hash = {
foo: 'bar',
method: -> {"I print the value of foo_method method: #{foo_method}"},
instance_var: -> {"I print the value of foo_variable instance variable: #{@foo_variable}"}
}
reshaped_hash = hash.reshape(self)
puts reshaped_hash[:method]
puts reshaped_hash[:instance_var]
@foo_variable = 50
reshaped_hash = hash.reshape(self)
puts reshaped_hash[:method]
puts reshaped_hash[:instance_var]
#I print the value of foo_method method: 10
#I print the value of foo_variable instance variable: 20
#I print the value of foo_method method: 10
#I print the value of foo_variable instance variable: 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment