I'm currently working on a codegolf challenge, and so I'm trying to use as few characters as possible.
This code:
#example data
x=[1,2,3]
a=5.times.map{5.times.map{' '}}
#problematic code:
a[b][c]=x.pop if a[b=rand(5)][c=rand(5)] == ' '
returns a (quite strange) error:
test.rb:5:in `<main>': undefined local variable or method `b' for main:Object (NameError)
Did you mean? b
Which boils down to "Can't find b
, did you mean b
?". (to which the answer is yes).
This only happens with a 2D array with an inline if statement.
This code also runs fine:
if a[b=rand(5)][c=rand(5)] == ' '
a[b][c]=x.pop
end
It seems like it should be exactly the same, but it behaves differently. Why is this?
I thought it might have something to do with precedence, but I had a look at the ruby precedence table and everything would seem to be what I expect, so I'm not sure.