[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Parallel assignment with a range, is it possilbe?

ceedeeeee

11/6/2004 10:50:00 AM

Is it possible to set a range of variables to a range of values using
Ruby's parallel assignment?

I've tried it briefly eg. something along the lines:

# set variables a,b,c,d etc to the value 1,2,3,4
[a..z] = [1..26]

Thanks.
1 Answer

Dave Burt

11/6/2004 11:18:00 AM

0

"Ceedeeeee" <ceedeeeee@hotmail.com> wrote in message
news:2e079d1b.0411060250.6c8c992c@posting.google.com...
> Is it possible to set a range of variables to a range of values using
> Ruby's parallel assignment?
>
> I've tried it briefly eg. something along the lines:
>
> # set variables a,b,c,d etc to the value 1,2,3,4
> [a..z] = [1..26]
>
> Thanks.

A Range is not a "range of variables", it's a range of values.

a..z is a Range from the value of the variable or method a to the value of
z

You can do:
h={}
('a'..'z').to_a.zip((1..26).to_a).each{|pair| h[pair[0]]=pair[1]}

to get a hash, if that will do - instead of variables a to z, you get
variables h['a'] to h['z']

I'm sure there's some way do get local variables this way...
local_binding=binding
('a'..'z').to_a.zip((1..26).to_a).each do |pair|
local_binding.instance_eval("#{pair[0]} = #{pair[1]}")
end

But this seems to only write to variables that already exist (ie if I set
z=1 before doing this, z will end up 26, but no other variables get set.)