任何人都可以帮我做这个简单的练习吗?
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)
答案 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 Minutes或Tutorial Point's ruby tutorial。我希望这有帮助!