This is hard to explain as a question but here is a code fragment:
n = "Bob"
class A
end
def A.greet
puts "Hello #{n}"
end
A.greet
This piece of code does not work because n is only evaluated inside A.greet when it is called, rather than when I add the method.
Is there a way to pass the value of a local variable into A.greet?
What about if n was a function?
Use metaprogramming, specifically the
define_singleton_methodmethod. This allows you to use a block to define the method and so captures the current variables.