Last active
April 13, 2016 08:56
-
-
Save vasilakisfil/e095e5ea133e23374b723fe14063725d to your computer and use it in GitHub Desktop.
Having fun with instance_exec in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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