我目前正在跳上Ruby列车,我有一些基本的Python知识,我希望能帮助我,但是我不清楚Ruby的'for'循环是如何工作的,我的感觉是它们在比较时的工作方式不同到Python。
一个例子可能是以下python代码:
print('Interest Calculator: ')
sumnum = eval(input('Enter your initial sum: '))
initnum = sumnum
rate = eval(input('Enter your interest rate: '))
noy = eval(input('Enter the number of years to calculate your interest for: '))
for i in range(noy):
sumnum = initnum * (1 + rate)
print('The value of your initial investment of £%s' %initnum, 'over the course of', noy, 'years is £%s' %sumnum)
产生以下内容(我随机输入数字):
Interest Calculator:
Enter your initial sum: 250
Enter your interest rate: 3
Enter the number of years to calculate your interest for: 7
The value of your initial investment of £250 over the course of 7 years is £1000
这里的for循环的Ruby等价物是什么?
我试着这样做:
puts 'Interest Calculator: '
puts 'Enter your initial sum: '
sumnum = gets
initsum = sumnum
puts 'Enter your interest rate: '
rate = gets
puts 'Enter number of years for your interest: '
noy = gets
for i in noy do
sumnum = initsum * (1 + rate)
end
puts "The value of your investment of £#{initsum} over the course of #{noy} years is £#{sumnum}"
然而,这会产生以下错误:
Interest Calculator:
Enter your initial sum:
250
Enter your interest rate:
3
Enter number of years for your interest:
7
~/RubymineProjects/ExploreRuby/InterestRate.rb:9:in `<top (required)>': undefined method `each' for "7\n":String (NoMethodError)
from -e:1:in `load'
from -e:1:in `<main>'
Process finished with exit code 1
非常感谢任何帮助。
答案 0 :(得分:2)
变化:
for i in noy do
sumnum = initsum * (1 + rate)
end
为:
noy.to_i.times do
sumnum = initsum.to_i * (1 + rate)
end
如果你坚持使用for
循环,那么:
for i in (1..noy.to_i) do
sumnum = initsum.to_i * (1 + rate)
end
ruby中的for
循环是each
的包装器,因此您要迭代的对象必须响应each
,noy
在这种情况下是一个字符串不是Enumerable
对象
答案 1 :(得分:0)
在Ruby中使用'for'通常使用'each'编写,这是更惯用的方式。 如果您想了解更多关于'for vs each'的信息,可以right here。
单线衬垫(消除打开挡块的'do')可能是:
noy.to_i.times { sumnum = initsum.to_i * (1 + rate) }
end