我需要创建简单的书籍信息列表(代码中的数据库),其中包含作者,流派,姓名,发布日期和页码。然后由作者搜索(按日期排序,按类型搜索(按作者排序)。最简单的方法是什么?
答案 0 :(得分:0)
您可以创建Book
类,然后将这些对象存储在Array
中。它非常简单,但您可能想要阅读一些关于Ruby和面向对象编程的内容。
class Book
attr_accessor :name
attr_accessor :author
attr_accessor :genre
def initialize name, author, genre
@name = name
@author = author
@genre = genre
end
def to_s
"book name: " + @name + "\nauthor: " + @author + "\ngenre: " + @genre
end
end
# create a few books
book_one = Book.new("Scary Book","Michael", "horror")
book_two = Book.new("Long Book", "Jim", "comedy")
book_three = Book.new("Short Book", "Pam", "romance")
# store them in an Array for sorting and searching
book_array = [book_one, book_two, book_three]
# sort the array by author
sorted_array = book_array.sort_by {|book| book.author}
# find the book(s) in the "romance" genre
romance_books = book_array.select {|book| book.genre == "romance"}