Aaron Fi
Aaron Fi

Reputation: 10396

Ruby hash initialization: is this niftyness possible?

This code works, of course:

@x = { :all => { :x => 1, :y => 2 } }

But this doesn't:

@x = { :abc, :all => { :x => 1, :y => 2 } }

Is there any way to do what I want here? i.e. I want two keys in a hash to each refer to the same (copy of a) value. But I only want to specify the value once.

Upvotes: 1

Views: 1797

Answers (2)

Gautam Rege
Gautam Rege

Reputation: 697

How about the following:

@x = { :all => tmp = { :x => 1, :y => 2 }, :abc => tmp.reject {|k,v| false} }

Upvotes: 0

Tobias
Tobias

Reputation: 4292

Yes, here:

@x = { :all => tmp = { :x => 1, :y => 2 }, :abc => tmp }

Upvotes: 6

Related Questions