638
know the features of your language
(lemmy.world)
Post funny things about programming here! (Or just rant about your favourite programming language.)
Ruby:
a || b(no
returnas last line is returned implicitly, no semicolon)EDIT: As pointed out in the comments, this is not strictly equivalent, as it will return
bifaisfalseas well as if it'snil(these are the only two falsy values in Ruby).Python:
return a or bi like it because it reads like a sentence so it somewhat makes sense
and you can make it more comprehensive if you want to:
return a if a is not None else bThis diverges from the OP code snippets if a has the value
False.I personally dislike this because when you read "or" you expect some boolean result not a random object :/
there's always the second option for you
For newer python people, they see return a or b and typically think it returns a boolean if either is True. Nope. Returns a if a is truthy and then checks if b is truthy. If neither are truthy, it returns b.
Not quite. If
ais not truthy, then the expressiona or bwill always returnb.So, there is never any reason to check the truthiness of
b.you can paste this in your repl to confirm it does not.
spoiler output
:::
Ah, good catch.
Typescript/Javascript too
Not strictly equivalent, since
||tests for truthiness, not just null.That's fair, but it's close enough that it functions identically
Only for the
nullcase. For other cases it doesn't function identically, since it also treats"",0andundefinedthe same asnull.Perl has both
$a || $band$a // $b.The
||version is older and has the value of$bif$ais any false value includingundef(which is pretty much Perl'snull/nil).The
//version has the value of$biff$aisundef. Other "false" values carry through.Ruby took both "no
returnrequired" and "no final semicolon required" from Perl (if not a few other things), I think, but it seems that//was Perl later borrowing Ruby's||semantics. Interesting.i.e.
0 || 1is1in Perl but0in Ruby. Perl can0 // 1instead if the0, which is a defined value, needs to pass through.