From: Trans Date: 2008-04-04T10:04:18+09:00 Subject: Re: using a range as a key On Apr 3, 5:30 pm, Alex Wayne wrote: > Michael Linfield wrote: > > I'm trying to achieve the effect of having a range of integers as a hash > > key, possible? > > > In effect I've tried: > > > range = 12345...12360 > > > hash = { range => "success!" } > > > hash[12349] > > > => nil > > This won't work. The range is a specific object, and that whole object > is the key > that points to "success!". SO in order to get success, you would need > to: > > hash[12345...12360] > > Hash won't do this on its own. Here is one way to go about this: > > class RangedHash > def initialize(hash) > @ranges = hash > end > > def [](key) > @ranges.each do |range, value| > return value if range.include?(key) > end > nil > end > end > > ranges = RangedHash.new( > 1..10 => 'low', > 21..30 => 'medium', > 41..50 => 'high' > ) > ranges[5] #=> "low" > ranges[15] #=> nil > ranges[25] #=> "medium" It's an interesting idea. What is needed is a Hash that can have key equality redefined. I seem to recall that 1.9 may have something for this, so as too allow indifferent key access, and it may work here too (using === instead of ==, or is it eql?) but I haven't explored it yet. T. > -- > Posted viahttp://www.ruby-forum.com/.