hguser
hguser

Reputation: 36018

The `+` in ruby

I am new in ruby, and I am reading the Progamming Ruby and following its examples.

This is the codes which teach the Inheritance and Messages:

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

  def to_s
    "Song:#@name \t#@artist\t#@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

This codes works fine.

However I found that if I change the to_s of KaraokeSong to this(Note there is no space between the + and the "[#@lyrics]"):

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

I will get the error:

in to_s': undefined method+@' for "[There for me, every time I've been away...]":String (NoMethodError)

But then I make a test:

name="kk"
puts name +"sfds"

This codes does not throw any errors.

What's the problem?

BTW, I am using ruby 2.0.0p247 (2013-06-27) [x64-mingw32]

Upvotes: 2

Views: 88

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107718

You're changing the method call there on the String. Previously, you're doing effectively this:

super.+(string)

Now, you're doing this super(+string). The +@ method isn't defined on String (it's defined on numbers though, and just returns a positive number), and that's why you're seeing this error.

Upvotes: 1

Related Questions