Ruby 同时为setter分配多个值:self.x=(y,z)会导致语法错误

Ruby 同时为setter分配多个值:self.x=(y,z)会导致语法错误,ruby,syntax,setter,getter-setter,Ruby,Syntax,Setter,Getter Setter,我试图使用两个参数定义一个类方法-title和author。当我试图传递参数时,我得到了一个参数错误 语法错误,意外的“,”,应为“)” 书名和作者=(“安德的游戏”,“奥森·斯科特卡片”) 在setter方法中是否不允许传递多个参数,或者是否缺少其他参数?对于以=结尾的方法,确实不能传递多个参数。setter方法不需要以=结尾,当然:您可以只做set\u title\u和\u author(title,author) 另一种选择是让该方法采用数组: def set_title_and_auth

我试图使用两个参数定义一个类方法-title和author。当我试图传递参数时,我得到了一个参数错误

语法错误,意外的“,”,应为“)” 书名和作者=(“安德的游戏”,“奥森·斯科特卡片”)


在setter方法中是否不允许传递多个参数,或者是否缺少其他参数?

对于以
=
结尾的方法,确实不能传递多个参数。setter方法不需要以
=
结尾,当然:您可以只做
set\u title\u和\u 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"]
如果您使用后者,我建议从风格上删除
集合
,只调用方法
title\u和\u author=
<代码>设置与
=
冗余

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")

=
符号是不必要的。请执行以下操作:

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

这对我很有用。

检查这个括号,不要在Ruby中创建“元组”。尝试这样使用它们将导致语法错误,无论是否与setter一起使用。另外,作为一个类方法(它不是)和一个实例方法/设置器(它是)是不相关的。这不是类方法,而是实例方法。术语“类方法”是为类本身调用的
Book.new
等方法保留的。
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