Reputation: 103
I am currently jumping onto the Ruby train and I have some basic Python knowledge, which I hoped would help me, however I am not clear as to how Ruby's 'for' loops work and my feeling is that they work differently when compared to Python.
An example could be the following python code:
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)
Which produces the following (I put random numbers in):
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
What would a Ruby equivalent of the for loop here be?
I tried to do it like so:
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}"
This however, produces the following error:
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
Any help is much appreciated.
Upvotes: 0
Views: 378
Reputation: 1318
Using 'for' in Ruby is typically written using 'each', this is the more idiomatic way. If you care to read more about 'for vs each' you can right here.
A one-line liner (eliminating the 'do' that opens your block) could be:
noy.to_i.times { sumnum = initsum.to_i * (1 + rate) }
end
Upvotes: 0
Reputation: 9762
change:
for i in noy do
sumnum = initsum * (1 + rate)
end
to:
noy.to_i.times do
sumnum = initsum.to_i * (1 + rate)
end
if you insist on using the for
loop then:
for i in (1..noy.to_i) do
sumnum = initsum.to_i * (1 + rate)
end
The for
loop in ruby is a wrapper around each
so the object you intend to iterate on must respond to each
, noy
in this case is a string an not an Enumerable
object
Upvotes: 2