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.
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 >
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With