Parallel assignment with a range, is it possilbe?

C

Ceedeeeee

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.
 
D

Dave Burt

Ceedeeeee said:
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.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top