假设我正在运行此代码片段。
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 后我也找不到。预先感谢您为我提供的任何资源。
最佳答案
如果您的函数定义未指定输入参数的默认值,则必须提供它们。
# 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
关于ruby - 我是否必须初始化类的所有成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10593170/