0

I have a class named Fraction that calculates the harmonic sum. Basically, I want to be able to input a value, and then the program be able to calculate the harmonic sum up to that number. For example, if a user inputs 3 then I want the output to be "harmonic 1: 1/1, harmonic 2: 3/2, harmonic 3: 11/6". This is what I have for the method so far.

print "Enter a value for your harmonic sum: "
x = gets.chomp.to_i

def harmonic_sum(x)
    (1..x).inject(Fraction.new(0)) do |a, i|
    harmonic = Fraction.new(1, i)
    puts "h#{i}: #{harmonic + a}"

    a + harmonic
    end
end

puts harmonic_sum

I keep getting an error that my argument is wrong. Any help would be appreciated!

8
  • harmonic_sum requieres a parameter, maybe x. Commented Mar 24, 2017 at 20:46
  • 1
    And what is Fraction? Commented Mar 24, 2017 at 20:48
  • Fraction is my class I created that calculates the harmonic sum Commented Mar 24, 2017 at 20:50
  • 1
    Please edit to reproduce the error message, including the line in which it occurred. Commented Mar 24, 2017 at 21:01
  • 2
    by the way, using proper indentation in your code makes it easier to read. Commented Mar 24, 2017 at 21:17

1 Answer 1

1

Right here you get an input:

x = gets.chomp.to_i

Then you define the method which requires one argument:

def harmonic_sum(x)

but here you call it with no arguments:

puts harmonic_sum

Instead, use puts harmonic_sum(x)

Sign up to request clarification or add additional context in comments.

2 Comments

Once I do that, it says I get an error in line 4 which is "def initialize (n, d)". It says "'initialize': wrong number of arguments (1 for 2) (ArgumentError)"
@Arayah yeah look at Fraction.new(0) - you're calling it with one argument but the Fraction initialize function needs 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.