我是否必须初始化类的所有成员变量?

时间:2012-05-15 01:41:08

标签: ruby class initialization

假设我已经运行了此代码段。

class Song
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end

  def to_s
    "Song: #{@name}--#{@artist} (#{@duration})"
  end
end

SongA = Song.new("Bicyclops", "Fleck", 260)
puts SongA.to_s

如果我将SongA = Song.new("Bicyclops", "Fleck", 260)替换为SongA = Song.new("Bicyclops", "Fleck"),则会收到错误消息。根据Ruby代码构造,这是正常的吗?

顺便说一句,我从here得到了例子。但即使在浏览this doc之后我也很难找到。提前感谢您指出的任何资源。

1 个答案:

答案 0 :(得分:2)

如果您的函数定义未指定输入参数的默认值,则必须提供它们。

  # Default artist is Nobody
  # Default duration is nil
  def initialize(name, artist='Nobody', duration=nil)
    @name = name
    @artist = artist
    @duration = duration
  end

然后您可以初始化它,省略您为其定义默认值的属性。

# Using lowercase songA instead of SongA since 
# ruby will treat the uppercase SongA as a constant...
songA = Song.new('Bicyclops')

您也不需要初始化initialize()中的所有类属性。可以在其他方法中添加和初始化它们

def other_method
  @other_prop = "Another property"
end
相关问题