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

我与影子孤独终老i 提交于 2019-12-11 17:59:33

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/10944555/m-one-m-two-m-three-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!