this post was submitted on 08 Dec 2023
622 points (96.4% liked)

Programmer Humor

32443 readers
1280 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 49 points 11 months ago* (last edited 11 months ago) (14 children)

Ruby:

a || b

(no return as last line is returned implicitly, no semicolon)

EDIT: As pointed out in the comments, this is not strictly equivalent, as it will return b if a is false as well as if it's nil (these are the only two falsy values in Ruby).

[–] [email protected] 13 points 11 months ago (1 children)

This doesn't work for booleans because false is not null but also not truthy. One of things I hate about ruby is that it doesn't have a native null coalescing operator.

[–] [email protected] 1 points 11 months ago

Yeah, you're quite correct, it's not exactly equivalent, I just went on auto-pilot because it's used so much for that purpose 🤖

It's much closer to being a true null-coalescing operator than 'OR' operators in other languages though, because there's only two values that are falsy in Ruby: nil and false. Some other languages treat 0 and "" (and no doubt other things), as falsy. So this is probably the reason Ruby has never added a true null-coalescing operator, there's just much fewer cases where there's a difference.

It's going to drive me mad now I've seen it, though 😆 That's usually the case with language features, though, you don't know what you're missing until you see it in some other language!

load more comments (12 replies)