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_method
method. This allows you to use a block to define the method and so captures the current variables.
n = "Bob"
class A
end
A.define_singleton_method(:greet) do
puts "Hello #{n}"
end
A.greet
You can use a global ($n = "Bob")...
Although I prefer Nemo157's way you can also do this:
n = "Bob"
class A
end
#Class.instance_eval "method"
A.instance_eval "def greet; puts 'Hello #{n}' end"
#eval Class.method
eval "def A.greet2; puts 'Hi #{n}' end"
A.greet
A.greet2
精彩评论