0

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.

Community
  • 1
  • 1
Shelvacu
  • 4,245
  • 25
  • 44
  • So `a[b][c]=x.pop if ...` does not run fine, but `a[b]=x.pop if ...` does? – sawa Jan 24 '16 at 20:13
  • @sawa yes, but I've removed the latter since I realized that of course array != `' '`, so the block of the if wasn't executing. My bad. – Shelvacu Jan 24 '16 at 20:17
  • @ndn see my comment, it's because in my 1d array example, the conditional evaluates to `false` so the block is never executed. If you add `|| true` the same error happens. It is a duplicate. – Shelvacu Jan 24 '16 at 20:21
  • @shelvacu, yea, my bad. Saw it afterwards – ndnenkov Jan 24 '16 at 20:22

0 Answers0