From: Alex Wayne Date: 2008-04-04T06:30:44+09:00 Subject: Re: using a range as a key 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" -- Posted via http://www.ruby-forum.com/.