I have a construction in my application for which I need a hash like this:
{ 1 => [6,2,2], 2 => [7,4,5], (3..7) => [7,2,1] }
So I would like to have same value for keys 3, 4, 5, 6 and 7.
Sure above example doesn't work cause Ruby is intelligent and sets hash key as given: it sets range as key :) So I can only access my value as my_hash[(3..7)]
and my_hash[3]
, my_hash[4]
and so on are nil.
Sure I can have a check or construction outside of hash to do what I need, however I am curious if it is possible to set a hash like this without using any loops outside hash declaration? If not, what is most elegant one? Thanks!
You could subclass Hash
to make it easier to construct such hashes:
class RangedHash < Hash
def []=(key, val)
if key.is_a? Range
key.each do |k|
super k, val
end
else
super key, val
end
end
end
It works the same as a normal hash, except when you use a Range key, it sets the given value at every point in the Range.
irb(main):014:0> h = RangedHash.new
=> {}
irb(main):015:0> h[(1..5)] = 42
=> 42
irb(main):016:0> h[1]
=> 42
irb(main):017:0> h[5]
=> 42
irb(main):018:0> h['hello'] = 24
=> 24
irb(main):019:0> h['hello']
=> 24
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