Search code examples
rubyrangeirbargument-error

bad value in range argument error - regarding range construction in ruby


I wrote the following snippet.

def add_me(num)
    result = 0
    (1..num).each { |i| result += i}
    result
end
puts add_me(STDIN.gets)

I received an argument error list_sum.rb:6:in 'AddMe': bad value for range (ArgumentError) the line # corresponds to line # in my editor.

I also experimented with things like foo = (1..num).to_a. But still receive the same error. What is going on? Ruby version 2.3.3. What am I missing? I should be able to use variables in ranges, no?


Solution

  • gets returns a string. You need to do gets.to_i, in order to turn the input into a number for your numeric range. Right now you’re trying to make a range where the start is the number 1 and the end is some string, and that is raising an ArgumentError.

    Also as an aside, ruby convention would tell you that your function should be named add_me. Ruby uses snake case, and anything that starts with a capital letter is typically assumed to be a class or constant (constant being all caps).