假设我已经运行了此代码段。
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代码构造,这是正常的吗?
答案 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