为什么我无法在Ruby中访问哈希?

时间:2018-10-17 13:27:46

标签: ruby

我将把 Book1 的数据添加到哈希 bl 中,但是当我运行代码时,它将返回我

  

:在“ booklist”中:错误的参数数量(给定0,应为1)(ArgumentError)

这是我的代码。

class Book
  attr_accessor :title, :author, :language, :classification, :isbn, :book_id, :borrow_status



  def initialize(title, author, language, classification, isbn, book_id, borrow_status)
    @title = title
    @author = author
    @language = language
    @classification = classification
    @isbn = isbn
    @book_id = book_id
    @borrow_status = borrow_status
  end



  def booklist(bl)
     bl = {
    "Title " => @title.title.split(/ |\_|\-/).map(&:capitalize).join(" "),
    "Author " => @author.title.split(/ |\_|\-/).map(&:capitalize).join(" "),
    "Language " => (@language.title),
    "Classification " => @classification,
    "ISBN " => @isbn.to_s,
    "Book ID" => @book_id.to_s,
    "Status" => @borrow_status
    }
    end


  def put_booklist
    booklist.each do |x , y|
      puts "#{x}" , "#{y}"
    end
  end


end

books1 = Book.new("lonely planet: ireland","damian harper","english","tourism",9781786574459,1,"available")
books1.put_booklist

我想知道这是怎么回事?

1 个答案:

答案 0 :(得分:3)

您的booklist方法需要一个参数,但是在此调用中您没有传递任何参数

booklist.each do |x , y|

无论如何,根据booklist的定义,您不需要或不使用该参数。将booklist移至

def booklist
  {
    "Title " => @title.title.split(/ |\_|\-/).map(&:capitalize).join(" "),
    "Author " => @author.title.split(/ |\_|\-/).map(&:capitalize).join(" "),
    "Language " => (@language.title),
    "Classification " => @classification,
    "ISBN " => @isbn.to_s,
    "Book ID" => @book_id.to_s,
    "Status" => @borrow_status
  }
end