在Ruby中使用gets.chomp的NoMethodError

时间:2015-04-18 02:51:04

标签: ruby methods undefined nomethoderror chomp

任何人都可以帮我做这个简单的练习吗?

class Item
  def percents()
    self * 100
  end
end

answer = gets.chomp
puts answer.percents()

结果是:

percents.rb:7:in `<main>': undefined method `percents' for "300":String (NoMethodError)

1 个答案:

答案 0 :(得分:2)

变量answer必须是Item对象才能拥有percents方法。或者,您可以从percents类中删除Item方法,并使其包含整数:

def percents(int)
   int * 100
end

answer = gets.chomp
puts percents(answer)

然而,最后一行并没有像你期望的那样做到。由于gets.chomp会返回您输入的字符串,因此您将乘以字符串&#34; 300&#34; 100,这意味着您的输出将如下所示:

2.2.2 :026 > puts percents(answer)
300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300
 => nil

您可以先使用to_i将答案转换为int,然后打印百分比

2.2.2 :027 > puts percents(answer.to_i)
30000
 => nil

那里看起来更好。现在,如果您想让answer成为课程Item的对象,那就更难了。

class Item
  def initialize(answer)
    @answer = answer
  end

  def percents
    @answer * 100
  end
end

item = Item.new(gets.chomp.to_i)
puts item.percents

您的输出与上面的内容相同:

2.2.2 :049 > puts item.percents
30000
 => nil

如果您有其他问题,请告诉我,因为我不能100%确定您尝试撰写的计划的意图。我建议您在学习Ruby的过程中查看一些Ruby教程,如Ruby in Twenty MinutesTutorial Point's ruby tutorial。我希望这有帮助!