Tom Tom - 1 month ago 7
Ruby Question

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

I'm trying to create a script to go through an index, look at each page number, and tell me what chapter of the book that entry is in. Here's an approximation of what I'm doing:

@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 number === page_range
puts "<a href=\"" + chapter_name + "\page" + number.to_s + "\">" + number.to_s + </a>"
end
end
end


find_chapter(1)
will spit out the string I want, but
find_chapter(15)
doesn't return anything. Is it not possible to use a range as a key like this?

Fab Fab
Answer

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" 
Comments