Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting few hash parameters with same value but different keys

Tags:

ruby

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!

like image 251
konnigun Avatar asked Dec 07 '22 08:12

konnigun


1 Answers

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
like image 144
Luke Avatar answered May 21 '23 15:05

Luke