Ryan Glass Ryan Glass - 1 year ago 58
Ruby Question

printing user input multiple times with different instances in ruby

is there a way to make this script run with just one puts? Where the user input would be what the puts statement prints out?

print "Which harmonic sums do you wish to calculate? "
sum = gets.to_i

def harmonic_sum(n)
(1..n).inject(Fraction.new(0,1)) {|r, i| r + Fraction.new(1,i) }

puts harmonic_sum(1)
puts harmonic_sum(2)
puts harmonic_sum(3)
puts harmonic_sum(4)
puts harmonic_sum(5)

Would I have to make a local variable in order to run this as a loop and if so what kind of loop would I run. I've see other posts saying a while loop or for loop would work, but which one would be better?

Answer Source
  1.upto(sum) do |n|
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download