(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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With