Ruby 类及其父类是否可以包含同名的成员变量?

Ruby 类及其父类是否可以包含同名的成员变量?,ruby,inheritance,Ruby,Inheritance,我举了下面的例子来说明。如果我在Song和KarokeSong类中同时使用name,我会得到一个错误 class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end def to_s "Song: #{@name}--#{@artist} (#{@duration})" end end class K

我举了下面的例子来说明。如果我在
Song
KarokeSong
类中同时使用
name
,我会得到一个错误

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

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

class KarokeSong < Song
  def initalize(name, kname, artist, duration, lyrics)
    super(name, artist, duration)
    @name = kname
    @lyrics = lyrics
  end

  def to_s
    "KS: #{@name}--#{@artist} (#{@duration}) [#{@lyrics}] **#{@name}**"
  end
end

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

songB = KarokeSong.new("John", "Casey", "The Band", 400, "And now, the...")
puts songB.to_s
class歌曲
def初始化(名称、艺术家、持续时间)
@name=name
@艺术家
@持续时间=持续时间
结束
def至美国
“歌曲:{@name}--{@artist}({@duration})”
结束
结束
卡罗基松班
def初始化(名称、名称、艺术家、持续时间、歌词)
超级(姓名、艺术家、持续时间)
@name=kname
@歌词
结束
def至美国
“KS:{@name}--{@artist}({@duration})[{@ly词}]**{@name}**”
结束
结束
songA=Song.new(“Bicyclops”,“Fleck”,260)
把songA带到
songB=KarokeSong.new(“约翰”,“凯西”,“乐队”,400,“现在是…”)
将songB.置于
下面是我在尝试运行该文件时收到的错误

stanley@ubuntu:~/Github/webdev_class/ruby$ ruby inheritance.rb
Song: Bicyclops--Fleck (260)
inheritance.rb:28:in `initialize': wrong number of arguments(5 for 3) (ArgumentError)
    from inheritance.rb:28:in `new'
    from inheritance.rb:28:in `<main>'
stanley@ubuntu:~/Github/webdev_class/ruby$ruby-heritation.rb
歌曲:Bicyclops-Fleck(260)
heritation.rb:28:在'initialize'中:参数数目错误(5代表3)(ArgumentError)
来自继承。rb:28:in'new'
来自继承。rb:28:in`'

我猜如果存在继承关系,则不允许使用两次名称
name
。我不确定这是否与Ruby不支持多重继承或V指针有关。提前感谢您对正在发生的事情提出的建议。

我认为问题在于卡拉ok歌曲并不是从歌曲中继承下来的


将KaraokeSong类定义更改为
class KaraokeSong

,以回答标题中的问题:实例变量绑定到对象,而不是类
@name
将始终引用给定对象中的同一变量,无论访问它的方法属于哪个类

super name     # assigns name to @name
@name = kname  # overwrites name with kname

class KaraokeSong
应该会让你走上正确的方向。天哪……完全忘记了
。即使更正了那个细节,我仍然会遇到类似的错误。检查问题的更新情况。@Casper:我不知道这是否是一个玩笑,但我在类定义和实例化同一类的对象时都将其拼写为
KarokeSong
。所以我认为这不重要。对不起,我的错,但是你在
KarokeSong
中把
initialize
错贴为
initialize
:-/