m.one + m.two + m.three doesn't work

2019-08-19 07:51发布

This is my code:

class Person
  def initialize(first_name, last_name, age)
    @first_name = first_name
    @last_name = last_name
    @age = age
  end

  def first_name
    puts @first_name
  end

  def last_name
    puts @last_name
  end

  def age
    puts @age
  end
end

class Musician < Person
  def initialize(first_name, last_name, age, instrument)
    @first_name = first_name
    @last_name = last_name
    @age = age
    @instrument = instrument
  end

  def instrument
    puts @instrument
  end
end

Then when I try to do the following:

m = Musician.new("George", "Harrison", 58, "guitar")
m.first_name + " " + m.last_name + ": " + m.age.to_s

I get an error:

in <main>': undefined method+' for nil:NilClass (NoMethodError)

Why can't I just concatenate the results of objects method?

标签: ruby return null
1条回答
看我几分像从前
2楼-- · 2019-08-19 08:14

all your methods return nil rather than the value you wish, that is, "puts" returns nil. just eliminate the "puts" and try again

查看更多
登录 后发表回答