Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you dynamically initialize multiple variables on one line in ruby? [duplicate]

Tags:

ruby

(I've only been coding for a few weeks and this is my first question here, so please bear with me!)

In ruby, I know that you can initialize multiple variables on a single line like this:

a, b = 1, 2

However, I am wondering if it is possible to initialize multiple variables in a loop that also generates their names. Here's some pseudocode that explains what I mean:

For X between 0 and 3, even_X = X * 2

This would set even_0 == 0, even_1 == 2, even_2 == 4, and even_3 == 6.

I realize that one can achieve the same functionality by iteratively creating an array and then calling on its members, but I am still curious if there is a way to do this.

Thanks!

like image 344
hoffm Avatar asked Feb 24 '26 06:02

hoffm


1 Answers

There is a way, using eval, but you would rather not want to use it (and I would even go that far to say that it might be better not to learn it until well later).

There is simply no case when you would use that instead of plain arrays.

For your example, one should use class Range and method map:

(0..3).map{|i| i * 2}
#=> [0, 2, 4, 6]

You can see that this has been done without declaring any variable - even i is alive just within the block passed to map. It doesn't exist afterwards.

like image 164
Mladen Jablanović Avatar answered Feb 25 '26 21:02

Mladen Jablanović