0

I am trying to create some simple programs as trying to learn Ruby and then move on to rails, I am just playing about to try and get used to the flow of how different types of code work variables, loops etc.

I am trying to create a simple book system were I already have 3 books in my hash and then I want to list the books already in the library in the console and then I want to be able to add new books and then also loop through and display the new list to the console.

require 'rubygems'

class GetDetailsFromUser
  books = {
      Eagle_Eye: 1,
      Eage_Eye1: 2,
      Eagle_Eye2: 3
  }

  books.each do |i|
    puts i
  end

  while true
    add = gets.chomp
    break if add.empty?
    books << add
  end

  puts 'New list is below'

  books.each do |i|
    puts i
  end
end

Were am I going wrong? I manage to print out the hash to the console, however, I get an error message

undefined method '<<' for {:Eagle_Eye=>1,...

Why is the method undefined? books << add? This should add a new book to the book hash table?

3 Answers 3

2

Add your second number with it. Here is a working example I wrote for you

Live Demo - VISIT THIS LINK

  books = {
      Eagle_Eye: 1,
      Eage_Eye1: 2,
      Eagle_Eye2: 3
  }


      books.each do |i|
        puts i
      end

      while true
        puts "What book would you like to add?"
        add = gets.chomp
        if add.empty? == true
            puts "Error - You did not enter a title for a book"
            break
        else
        books.max_by do |book,id|
                 @list_number = id
                end
         books[add.to_sym]=@list_number
         break
        end
      end

  puts 'New list is below'

  books.each do |i|
    puts i
  end
Sign up to request clarification or add additional context in comments.

Comments

0

refactored version of @ExecutiveCloser

books = {
    Eagle_Eye: 1,
    Eage_Eye1: 2,
    Eagle_Eye2: 3
}

books.each do |i|
    puts i
end

add = ""

while add.empty? do
    puts "What book would you like to add?"
    add = gets.chomp

    books[add.to_sym] = books.size + 1 unless add.empty?
end

puts 'New list is below'

books.each do |i|
    puts i
end

https://repl.it/CDK2/3

Comments

0

Ruby has a documentation site. E. g. Hash documentation clearly states, that there is no method << defined on the hash instance.

<< method is defined on Array.

Why would you expect “books << add should add a new book to the book hash table”?

There is another glitch within your code: you execute everything on class definition level, which makes absolutely no sense in this case.

Since it is unclear what do you want to achieve, I am unable to provide a ready-to-go-with solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.