From: "Hal E. Fulton" Date: 2001-11-07T06:45:28+09:00 Subject: [ruby-talk:24469] Re: Range in Hash array? ----- Original Message ----- From: Newsgroups: comp.lang.ruby To: ruby-talk ML ; Sent: Tuesday, November 06, 2001 3:26 PM Subject: [ruby-talk:24456] Range in Hash array? > I'd like to be able to do something like: > {1..100=>"a",101..300=>"c", 500..1000=>"r"} > > The syntax accepts it, but it doesn't behave the way I'd like (always > comes up nil). > > Anyway to pull this off (currently using a case statement). I think the basic problem is that Ruby is doing exactly what you tell it, rather than what you want. Don't you hate computers for that? A Range is itself an object. When you use it as a hash key, you are associating the range itself with the given value... NOT each item of the range with the given value. So your hash above has only three keys, not 801 as I think you want. You *could* create a hash of 801 elements easily this way: h = {} 1..100.each {|x| h[x] = "a" } 101..300.each {|x| h[x] = "c" } 500..1000.each {|x| h[x] = "r" } There are probably more elegant ways, though nothing comes to mind... unless you wanted to just hide your case statement inside a method (essentially a function returning the value based on the key). This would save a little memory but would slow downyour runtime a little. Hal