Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

New to Ruby and have run out of ideas. I have an array of books that I would like to 1) Shelve 2) Find which shelf it is on 3) Remove it from the associated shelf if found. For brevity I have an array of 6 books. Each shelf contains 5 books.

library_catalog = [ "Book1", "Book2", "Book3", "Book4", "Book5", "Book6" ]
shelves = Hash.new(0)
catalog_slice = library_catalog.each_slice(5).to_a
count = 1

catalog_slice.each do | x |
shelves.merge!(count=>x)
count+=1
end

From this I know have a Hash w/ arrays as such

{1=>["Book1", "Book2", "Book3", "Book4", "Book5"], 2=>["Book6"]}

This is where I'm having trouble traversing the hash to find a match inside the array and return the key(shelf). If I have title = "Book1" and I am trying to match and return 1, how would I go about this?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

I think this should work.

shelves.select { |k,v| v.include?("Book1")}.keys.first

selected the hashes that have a value equal to the title you are looking for (in this case "Book1") get the keys for these hashes as an array get the first entry in the array.

to remove the Book from the shelf try this:

key = shelves.select { |k,v| v.include?("Book1")}.keys.first
shelves[key].reject! { |b| b == "Book1" }

get a reference to the array and then reject the entry you want to remove

share|improve this answer
    
I had tried this approach but didn't know about .keys.first which returned the data I required. Quick follow up. Now that I have the key, and the Book, is there a built in method to remove Book1 from Shelf 1? –  Strawman Sep 5 at 2:28
    
Thank you kindly. I'll add this to my toolbox and run through some trails to get it down. –  Strawman Sep 5 at 3:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.