vendredi 30 août 2019

Is there a reason for an if statement followed by another to end the line with an 'and' operator (&&) in ruby?

I'm trying to figure out why this works and whether it's a bad practice.

The following code will throw a SyntaxError:

if true &&
  puts "ok"
end

Though the following code will not, it will execute as expected:

if true &&
  if true
    puts "ok"
  end
end

I came across this while writing a ruby script with an if statement containing a big chain of conditions, so I put each one in a separate line and then I commented out the last one and executed the script. At the moment, I realized that the if statement ended with the && operator. While I expected it to throw, I was amazed that it didn't because another if statement followed right after.

My ruby version is ruby 2.2.6p396 (2016-11-15 revision 56800) [x86_64-darwin16].

Aucun commentaire:

Enregistrer un commentaire