Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create three objects with one line of code?

How would I create three empty hashes with a single line of code?

I know that a = b = c = Hash.new won't work, since that'll create three references to the same Hash object.

a,b,c = Hash.new will assign the Hash to a, but b and c remain nil.

I know I could do a, b, c = Hash.new, Hash.new, Hash.new, but that doesn't look very DRY.

like image 552
omninonsense Avatar asked Dec 09 '25 01:12

omninonsense


2 Answers

As I posted as a comment, I think a, b, c = {}, {}, {} is the best way, because it's short, and easy to read. If you really want to do it in a more complicated way, something like this will work:

>> a, b, c = Array.new(3) { Hash.new } #=> [{}, {}, {}]
>> a #=> {}
>> b #=> {}
>> c #=> {}
like image 136
Michael Kohl Avatar answered Dec 10 '25 18:12

Michael Kohl


I am not really sure if I would use that, but it is possible:

a, b, c = 3.times.map { Hash.new }
# or
a, b, c = (1..3).map { Hash.new }
like image 32
Marcel Jackwerth Avatar answered Dec 10 '25 18:12

Marcel Jackwerth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!