Is it possible to use a range as a key for a hash in Ruby? Is it possible to use a range as a key for a hash in Ruby? ruby ruby

Is it possible to use a range as a key for a hash in Ruby?


You can use a range for Hash keys and you can look up keys very easily using select like this:

@chapters = { 1 => "introduction.xhtml", 2..5 => "chapter1.xhtml",               6..10 => "chapter2.xhtml", 11..18 => "chapter3.xhtml",                                                       19..30 => "chapter4.xhtml" } @chapters.select {|chapter| chapter === 5 } #=> {2..5=>"chapter1.xhtml"} 

If you only want the chapter name, just add .values.first like this:

@chapters.select {|chapter| chapter === 9 }.values.first #=> "chapter2.xhtml" 


Here's a concise way of returning just the value of the first matching key:

# setupi = 17; hash = { 1..10 => :a, 11..20 => :b, 21..30 => :c }; # find keyhash.find { |k, v| break v if k.cover? i }


Sure, just reverse the comparison

if page_range === number

Like this

@chapters = {  1 => "introduction.xhtml",  2..5 => "chapter1.xhtml",  6..10 => "chapter2.xhtml",  11..18 => "chapter3.xhtml",  19..30 => "chapter4.xhtml" }def find_chapter(number)  @chapters.each do |page_range, chapter_name|    if page_range === number      puts chapter_name    end  endendfind_chapter(1)find_chapter(15)# >> introduction.xhtml# >> chapter3.xhtml

It works this way because === method on Range has special behaviour: Range#===. If you place number first, then Fixnum#=== is called, which compares values numerically. Range isn't a number, so they don't match.