ooransoy
ooransoy

Reputation: 797

Bad value for range

When I run the following code:

def db(y)
  return self % y == 0
end

puts "To number:"
n = gets.chomp

for i in 1..n
  if i.db(3)
    puts "Fizz!"
    if i.db(5)
      puts "FIZZBUZZ!"
    end
  elsif i.db(5)
    puts "Buzz!"
  else
    puts i
  end
end

I get a "bad value for range" error. Why does this happen how do I fix it? Normal ranges that use variables for some values work perfectly including for loops, why does this not work?

Note: I want the for loop to stay as a for loop.

Upvotes: 13

Views: 22552

Answers (2)

falsetru
falsetru

Reputation: 369094

gets returns String.

You need to convert it to Fixnum using String#to_i.


Replace the following line:

n = gets.chomp

With:

n = gets.chomp.to_i

Upvotes: 7

Arup Rakshit
Arup Rakshit

Reputation: 118271

Just do as below :

n = gets.chomp.to_i

gets.chomp will give you String instance. You need to make it as Fixnum. Otherwise 1.."4" for e.g is not a valid range. so error "bad value for range" error. String#to_i is your friend.

2.0.0p0 :001 > 1.."2"
ArgumentError: bad value for range
    from (irb):1
    from /home/kirti/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'
2.0.0p0 :002 > 1..2
 => 1..2 
2.0.0p0 :003 > 

Upvotes: 17

Related Questions