The `+` in ruby

  • 本文关键字:ruby in The ruby
  • 更新时间 :
  • 英文 :


我是ruby的新手,我正在阅读Progamming Ruby并遵循它的示例。

这是教导Inheritance and Messages:的代码

class Song
  def initialize(name, artist, duration)
    @name=name;
    @artist=artist;
    @duration=duration;
  end
  def to_s
    "Song:#@name t#@artistt#@duration"
  end
end
class KaraokeSong < Song
  def initialize(name, artist, duration, lyrics)
    super(name, artist, duration);
    @lyrics=lyrics;
  end
  def to_s
    super + "[#@lyrics]";
  end
end
song=KaraokeSong.new("There for me", "Sarah", 2320, "There for me, every time I've been away...")
puts song.to_s

这个代码运行良好。

然而,我发现如果我将KaraokeSongto_s更改为这个(注意,+"[#@lyrics]"之间没有空格):

  def to_s
    super +"[#@lyrics]";
  end

我会得到错误:

to_s': undefined method+@'中表示"[在我身边,每次我离开了…]":字符串(NoMethodError)

但后来我做了一个测试:

name="kk"
puts name +"sfds"

此代码不会引发任何错误。

怎么了?

顺便说一句,我正在使用ruby 2.0.0p247 (2013-06-27) [x64-mingw32]

您正在更改String上的方法调用。以前,您正在有效地执行以下操作:

super.+(string)

现在,您正在执行super(+string)+@方法没有在String上定义(它是在数字上定义的,只返回一个正数),这就是为什么您会看到这个错误。

最新更新