Not really. Technically, you could do something like this:
def bar(&block)
ary = block.call
ary.each_with_index{|s,i| eval("#{s}=#{i}", block.binding)}
end
==>nil
bar{[:a,:b,:c]}
==>[:a, :b, :c]
[a,b,c]
==>[0, 1, 2]
This would create local variables with those values. However, they
wouldn't be accessible in anything other than irb:
mark@eMac% ruby
def bar(&block)
ary = block.call
ary.each_with_index{|s,i| eval("#{s}=#{i}", block.binding)}
end
bar{[:a,:b,:c]}
p [a,b,c]
-:6: undefined local variable or method `a' for main:Object (NameError)
mark@eMac%
This is because ruby decides at _compile time_ whether an identifier
represents a variable or a method call. Since Ruby doesn't see
anything being assigned to a b and c at compile time, it assumes they
are methods, and raises an error.
You could hack around this by pre-defining your variables, but that's ugly.
mark@eMac% ruby
def bar(&block)
ary = block.call
ary.each_with_index{|s,i| eval("#{s}=#{i}", block.binding)}
end
a,b,c = *
bar{[:a,:b,:c]}
p [a,b,c]
[0, 1, 2]
mark@eMac%
HTH,
Mark
···
On Fri, 3 Dec 2004 03:27:45 +0900, itsme213 <itsme213@hotmail.com> wrote:
def foo
bar [:a, :b, :c]
a
b
c
end
I would like a, b, and c to be local variables with values 1, 2, 3
(positions of :a, :b, :c). Is there some implementation of
def bar (symbol_list)
symbol_list.each_with_index { |s, i|
???
}
end
that will do this?