Starting Ruby, need help!

I creared a book to write name and age of people in it, and when name is ‘enter’, it should show me all names and ages I’ve entered, but it dosen’t
But it does when you do it without class method, whats wrong?
Help plz

You are better off thinking of everything as instance based: instance variables and instance methods.

So start off with a constructor, to create your names map:

class Book
  def initialize
    @names_map = {}
  end

end

This creates a hash map, which you can use later.
You do not need the option[:name] - you only have one pair of values to remember, so just use variables to store the input name and age:

  def add
    print "Enter name: "
    name = gets.strip
    if name == ''
      show_all 
    end

    print "Enter age: "
    age = gets.strip

    @names_map[name] = age
  end

Finally, put the age part into an ‘else’ block, as else it gets called even after entering an empty name:

  def add
    print "Enter name: "
    name = gets.strip
    if name == '' # no name entered, so show all the names
      show_all 
    else # we got a name, so get the age
      print "Enter age: "
      age = gets.strip
      # and enter the pair into the hash map
      @names_map[name] = age
    end
  end

Your show_all method now needs to work with @names_map, but otherwise is ok.

1 Like

so, its all cause constructor…
I’m surprised, I thought that, if its only 1 object it would be the same if create the variable/hash in the class method
Thanks anyway!

Yes, you could move the line creating the @names_map to the start of the add method.

The difference though is that each call to the add loop would make a new, empty map, meaning you would not have any names to show - give it a try!

Omg! New empty hash with every loop… Why i didn’t think about such simple thing before …

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs