James007
James007

Reputation: 3

Bad value for range caused by code block

When I run the following code:

cnum = randNum = 0
solutions = []
result = Hash.new

print "What's the number of people playing? "
n = gets.chomp.to_i

while cnum < n
    cnum += 1
    loop do
        randNum = rand(1 .. n)
        break unless (solutions.include? randNum) || randNum == cnum
        if solutions.include? n = false # If n isn't in the solution
            r = rand(1 ... n)
            randNum = r
            result[result.key(r)] = n
        end
    end
    solutions.push randNum
    result[cnum] = randNum
end

result.each do |player, result|
    print "Player #{player}, your player is Player #{result}"
    gets.chomp
end

I get the following error:

gbourdon@Thor-Mint ~/workspace/secretSanta $ ruby code.rb
What's the number of people playing? 5
code.rb:11:in `block in <main>': bad value for range (ArgumentError)
        from code.rb:10:in `loop'
        from code.rb:10:in `<main>'

However, when I remove this part of the code:

if solutions.include? n = false # If n isn't in the solution
            r = rand(1 ... n)
            randNum = r
            result[result.key(r)] = n
        end

The program works (albeit with a few bugs that the above code snippet's goal is to fix). Why is this, and what can I do to fix it? In addition, why does the error occur only when that block of code is added?

Upvotes: 0

Views: 153

Answers (1)

Simple Lime
Simple Lime

Reputation: 11035

Ruby is seeing this line as

if solutions.include?(n = false) # If n isn't in the solution

So, you're assigning n to false and checking if that is in the solutions. If not, you loop again, this time with n still equal to false and then try to create a new Range:

randNum = rand(1 .. n)

and that error's out, because since n == false, you are trying to create a Range from 1 to false and end up erring out.

You probably meant to check for

if solutions.include?(n) == false # If n isn't in the solution

or, more succinctly

if !solutions.include? n # If n isn't in the solution

or

unless solutions.include? n # If n isn't in the solution

Upvotes: 2

Related Questions