Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 916
ooransoy Avatar asked Jan 11 '14 19:01

ooransoy


2 Answers

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 > 
like image 159
Arup Rakshit Avatar answered Nov 17 '22 07:11

Arup Rakshit


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
like image 36
falsetru Avatar answered Nov 17 '22 08:11

falsetru