Hello Ruby Fans,
I’m working on the ruby section of the pleac project,
(http://pleac.sourceforge.net) because I think a good way to learn a new
language is trying to explain it to somebody else.
There are a few hundred code snippnets from the famous perl cookbook,
and one of it is perls local function:
You can give a global variable inside a block a new value. This is
slightly different from normal local variable, because it really changes
the global variable. I think it is sometimes even useful, when you need
to change the predefined global variables, but want to automatically
restore them after you are done.
The phyton documenter said that it is not possible in phyton.
But this is ruby, so there should be a solution.
I came up with the following:
def local(var)
eval(“save = #{var.id2name}”)
result = yield
eval("#{var.id2name} = save")
result
end
example usage
def print_age
puts "Age is #{$age}"
end
$age = "to small"
print_age()
local(:$age){
$age = 23
print_age()
}
print_age()
It prints the following:
to small
23
to small
It works quite well, but I like to know if I can get rid of the eval().
I already have my variable as symbol, so I think it must be possible
somehow to restore the variable from the symbol, without use of eval.
Do you have an idea for a more elegant solution?
Regards
Karsten Meier
Hamburg * Germany