Skip to content

Instantly share code, notes, and snippets.

@sj26
Created January 5, 2012 08:46
Show Gist options
  • Save sj26/1564308 to your computer and use it in GitHub Desktop.
Save sj26/1564308 to your computer and use it in GitHub Desktop.
# a class to play with
class Zoo
def animals
['bison', 'cat']
end
end
# add zebras method to the class
zebras = lambda do
puts "look, i have accesss to the instance scope "+ animals.inspect
end
Zoo.class_eval do
define_method(:zebras, &zebras)
end
#this works
z= Zoo.new
z.zebras
# we need a lions method with a new argument
lions = lambda do |an_argument|
puts "look #{an_argument}, i do not have access to the instance scope "+animals.inspect
end
# but we want the method to still be able to be called on the instance with no args,
# so we need to modify the method before being passed to define method
Zoo.class_eval do
define_method(:lions, lambda do
instance_exec("fine, sir", &lions)
end)
end
# but this will fail, because the lambda "lions" is no longer being executed in instance scope
z.lions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment