Ruby: export variable into local namespace
I want to programmatically insert a 开发者_开发知识库new variable into the local Ruby namespace. For example, I want to be able to write
label = 'some_name'
# some code equivalent to
# some_name = 3
# but using only 'label' to get the name.
puts some_name # returns 3
What do I put in the middle here to get this done?
I've answered another SO question similar to this. The short answer is this, if you specifically want to create a local variable with the name of it based on the value of another variable, then there is no way to do it. It you just want to make seem as though you've created a local but it is really ruby magic, then something like @mikong's answer is one way to go.
Note that if you relax your contraint and are happy to create an instance variable instead, then you can do it.
label = 'some_name'
self.instance_variable_set("#{label}", 3)
puts @some_name
You can even dynamically define an accessor and then you can get rid of the unsightly @, but once again you will simply have a method masquerading as a local rather than a real local variable.
The following is not exactly code between the 2 lines that you mentioned above:
class Example
attr_accessor :label
def method_missing(name, *args, &block)
return some_processing if name == label.to_sym
end
def some_processing
3 # of course, this can be something more complicated
end
def test
@label = 'some_name'
puts some_name
end
end
Nonetheless it seems to work with what you need. The mechanism has changed from what you gave (label is now an attribute). Also, technically, it's not a variable but a method with a dynamic name that returns what you need.
Personally, I think your requirements seem a little bit dangerous in that the "variable" name changes. I would probably not use the code in my example. I guess depending on the project requirements, I'll think of a different approach.
label = 'some_name'
eval "#{label} = 3"
puts eval "#{label}"
puts local_variables
Note that you would presumably never have an opportunity to execute...
puts some_name
...because if you knew what local variables you were going to create there would be no need to name them with run-time code. And that's good, because the interpreter will not be able to puts some_name
directly because it never parsed an assignment for some_name. But it is there and it is a local, as puts local_variables
is able to show.
精彩评论