Menu
Coddy logo textTech

Recap - Library Card

Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 6 of 57.

challenge icon

Challenge

Medium

Complete the class LibraryCard. initialize(name, limit = 3) stores the name and the loan limit and starts with no borrowed titles. borrow(title) returns true and adds the title, unless the card is at its limit or already holds that title, in which case it returns false. give_back(title) returns true when it removed the title. to_s returns Ada: 2/3 (Dune, Emma) with the titles in borrowing order, or Ada: 0/3 when nothing is borrowed.

The supplied code reads the name and the limit (- for the default), then commands +title or -title. It prints ok or no for each command and finally the card.

Your code goes in library_card.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'library_card'

# Supplied input/output code: keep it as it is
input = []
while (line = gets)
  input << line.chomp
end
card = input[1] == "-" ? LibraryCard.new(input[0]) : LibraryCard.new(input[0], input[1].to_i)
input.drop(2).each do |cmd|
  title = cmd[1..]
  done = cmd.start_with?("+") ? card.borrow(title) : card.give_back(title)
  puts done ? "ok" : "no"
end
puts card

All lessons in Object Oriented Programming

Practice on your own: Online Ruby compiler