From: Glenn Jackman Date: 2009-08-14T03:00:16+09:00 Subject: Re: Assignment from within a block? At 2009-08-13 07:23AM, "Gerald Ebberink" wrote: > On Thu, 2009-08-13 at 09:37 +0000, Glenn Jackman wrote: > > > At 2009-08-13 03:54AM, "Gerald Ebberink" wrote: > > > require 'bigdecimal' > > > > > > var1 = 10 > > > var2 = 20 > > > ["var1","var2"].each do |v| > > > v = BigDecimal.new(v.to_s) > > > end > > > var1.class > > > > > > Why isn't var1 changed, and how do I get the behaviour I want (and this > > > is ofcourse not for just to vars) > > > > I suspect you want > > > > var1, var2 = [var1, var2].collect {|v| BigDecimal.new(v.to_s)} > > > > [var1,var2].collect {|v| v.class} # => [BigDecimal, BigDecimal] > > > Yes this would be the preferred solution if I would know which vars > would be in the array. But the array is filled during operation and > of arbitrary length (not nil). I wondered why you had an array of strings. You just need to eval the variable name string. bigs = variable_names.collect {|v| BigDecimal.new(eval(v).to_s)} If you're creating the BigDecimal objects in a different context than where the variables exist, you need to obtain that context: var1, var2 = 10,20 def convert_to_big(varnames, context) # local variables "var1" and "var2" don't exist here # but they are in the binding "context" varnames.collect {|v| BigDecimal.new(eval(v, context).to_s)} end bigs = convert_to_big(["var1", "var2"], binding) -- Glenn Jackman Write a wise saying and your name will live forever. -- Anonymous