๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Project: Library

A library program keeps a shelf of books and can list them. This project builds the shelf from a Book class and an array.

The Book class

This program makes one book and prints its title. The title goes in at Book.new and comes back out through the reader.

class Book
  attr_reader :title

  def initialize(title)
    @title = title
  end
end

book = Book.new("Emma")
puts book.title

A shelf listed with numbers

This program puts two books on a shelf and lists them. The counter starts at 1 and grows by one for each book.

class Book
  attr_reader :title

  def initialize(title)
    @title = title
  end
end

shelf = []
shelf.push(Book.new("Emma"))
shelf.push(Book.new("Hamlet"))
number = 1
shelf.each do |book|
  puts "#{number}. #{book.title}"
  number += 1
end

Adding a book grows the shelf

This program prints the shelf length before and after one push. The length grows from 0 to 1.

class Book
  attr_reader :title

  def initialize(title)
    @title = title
  end
end

shelf = []
puts shelf.length
shelf.push(Book.new("Emma"))
puts shelf.length

Example

class Book
  attr_reader :title

  def initialize(title)
    @title = title
  end
end

shelf = []
shelf.push(Book.new("Emma"))
shelf.push(Book.new("Hamlet"))
number = 1
shelf.each do |book|
  puts "#{number}. #{book.title}"
  number += 1
end
puts "Type one more title"
title = gets.chomp
shelf.push(Book.new(title))
number = 1
shelf.each do |book|
  puts "#{number}. #{book.title}"
  number += 1
end

Key points

  • The Book class stores one title for each book.
  • attr_reader :title lets code outside the class read the title.
  • The shelf is an array that holds the books in order.
  • push adds one book to the end of the shelf.
  • each walks the shelf one book at a time.
  • A counter gives each listed book its number.

In this example, the typed line is Dune. The program first lists the two books already on the shelf with numbers. Then it asks for one more title and reads the typed line with gets. A new Book goes on the shelf and the list prints again with all three books.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

What does attr_reader :title give the Book class?