2

假设我正在运行此代码段。

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 代码结构,这正常吗?

顺便说一句,我从这里得到了例子。但即使在浏览完这个文档后我也找不到问题。提前感谢您为我提供的任何资源。

4

1 回答 1

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
于 2012-05-15T01:43:20.200 回答