From: Robert Dober Date: 2008-04-04T17:42:57+09:00 Subject: Re: using a range as a key On Fri, Apr 4, 2008 at 3:04 AM, Trans wrote: > > > > 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/. > > The basic problem I am seeing is that by accessing a hash with ranges as keys by elements of these ranges we simply lose our constant lookup time. I have some difficulties that we can come up with hash functions that yield the same value for the range and all its elements and different values for most other ranges. Another issue would of course be how to define behavior in case of overlapping ranges - undefined would probably the best one can come up without needing to traverse the whole hash for each update. Well if we sacrifice constant lookup time of course search trees might indeed solve OP's problem. Cheers Robert -- http://ruby-smalltalk.blogspot.com/ --- Whereof one cannot speak, thereof one must be silent. Ludwig Wittgenstein