谁能帮我做这个简单的练习?
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)
谁能帮我做这个简单的练习?
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)
变量answer
必须是Item
对象才能拥有该percents
方法。或者,您可以percents
从类中删除该方法Item
,并让它接受一个整数:
def percents(int)
int * 100
end
answer = gets.chomp
puts percents(answer)
但是,最后一行不会像您期望的那样做。由于gets.chomp
返回输入字符串,您将字符串“300”乘以 100,这意味着您的输出将如下所示:
2.2.2 :026 > puts percents(answer)
300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300300
=> nil
您可以先使用 将答案转换为 int,to_i
然后打印百分比
2.2.2 :027 > puts percents(answer.to_i)
30000
=> nil
那里,看起来更好。现在,如果您想让您answer
的对象成为 class 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 Twen0 Minutes或Tutorial Point 的 ruby 教程。我希望这有帮助!