m.one + m.two + m.three 不起作用 [英] m.one + m.two + m.three doesn't work

查看:39
本文介绍了m.one + m.two + m.three 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

我收到一个错误:

': undefined method+' for nil:NilClass (NoMethodError)

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

为什么我不能只连接对象方法的结果?

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

推荐答案

你所有的方法都返回 nil 而不是你想要的值,即puts"返回 nil.只需消除看跌期权"并重试

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

这篇关于m.one + m.two + m.three 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆