Why does this parse?

M

Michael Campbell

Just ran down an interesting 'bug' in my code, but I'm confused as to
why it parses at all. Can someone explain to me what the parser is
doing in this case? (Please cc: me directly also please; I don't
want to miss the answer.)

if (x != y ||
x != z
y != z)
puts "foo"
end


(notice the missing "||" after the second comparison)
 
T

ts

M> if (x != y ||
M> x != z
M> y != z)
M> puts "foo"
M> end

ruby see it as a block, the last expression will give it the value for the
test

uln% ruby -e 'if (1 != 1 || 1 != 1; 1); puts "ok"; end'
ok
uln%

uln% ruby -e 'if (1 != 1 || 1 != 1; nil); puts "ok"; end'
uln%


Guy Decoux
 
S

Shashank Date

Michael said:
Just ran down an interesting 'bug' in my code, but I'm confused as to
why it parses at all. Can someone explain to me what the parser is
doing in this case? (Please cc: me directly also please; I don't
want to miss the answer.)

if (x != y ||
x != z
y != z)
puts "foo"
end

My guess: it is parsing it as two expressions, like so:

if ( x != y || x != z; y != z )
<--- first -----> <-- 2nd -->

Ruby is very expressio-oriented.
(notice the missing "||" after the second comparison)

HTH,
-- shanko
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,432
Latest member
GTRNorbert

Latest Threads

Top