我试图使用两个参数 - title和author来定义一个类方法。当我试图传递我的论点时,我得到了一个参数错误
语法错误,意外',',期待')' book.set_title_and_author =(" Ender的游戏"," Orson Scott Card")
class Book
def set_title_and_author= (title, author)
@title = title
@author = author
end
def description
"#{@title}was written by #{@author}"
end
end
book = Book.new
book.set_title_and_author= ("Ender's Game", "Orson Scott Card)
p book.description
我不允许在我的setter方法中传递多个参数,或者我还缺少其他什么?
答案 0 :(得分:4)
您确实无法将多个参数传递给以=
结尾的方法。但是,setter方法不需要以=
结尾,当然:你可以set_title_and_author(title, author)
。
另一种方法是让方法采用数组:
def set_title_and_author= (title_and_author)
@title, @author = title_and_author
end
#...
book.set_title_and_author= ["Ender's Game", "Orson Scott Card"]
如果您执行后者,从风格上讲,我建议您删除set
并调用方法title_and_author=
。 set
=
是多余的。
答案 1 :(得分:0)
class Book
def set_title_and_author(title, author)
@title = title
@author = author
end
def description
"#{@title}was written by #{@author}"
end
end
book = Book.new
book.set_title_and_author("Ender's Game", "Orson Scott Card")
p book.description
但更明确的方法将是
class Book
attr_accessor :title, :author
def description
"#{@title}was written by #{@author}"
end
end
book = Book.new
book.title = "Ender's Game"
book.author = "Orson Scott Card"
p book.description
最后使用构造函数来设置属性(并避免不必要的可变性)要好得多
book = Book.new("Ender's Game", "Orson Scott Card")
答案 2 :(得分:0)
=
符号是不必要的。请执行以下操作:
class Book
def set_title_and_author(title, author)
@title = title
@author = author
end
def description
"#{@title} was written by #{@author}"
end
end
book = Book.new
book.set_title_and_author("Ender's Game","Orson Scott Card")
p book.description
这对我有用。