Project

General

Profile

Actions

Feature #18332

open

a ? b

Feature #18332: a ? b

Added by dorianmariefr (Dorian Marié) almost 4 years ago. Updated almost 4 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:106041]

Description

It would be a shortcut for a ? b : nil:

e.g.

"#{current_path == "/" ? "font-bold"}"
"#{user.admin? ? "text-red-600"}"

Doing a && b returns false which converted to a string gives "false".

When nil converts to a string it gives "".

I would use it mostly in string interpolations.

Updated by zverok (Victor Shepelev) almost 4 years ago Actions #1 [ruby-core:106042]

puts "#{'font-bold' if true}"
# => font-bold

Updated by dorianmariefr (Dorian Marié) almost 4 years ago Actions #2 [ruby-core:106043]

Thanks, I still think the root? ? "font-bold" reads better than "font-bold" if root? though

Updated by zverok (Victor Shepelev) almost 4 years ago Actions #3 [ruby-core:106044]

Well, obviously that's a matter of personal taste, but for a one-branch if the postfix form seems to read naturally ("this item will have class "font-bold" if it is root).

So it might be that cond ? result reads better for you because you invented it starting to think from cond ? result : else (which, should we say, is quite esoteric on itself, we just got used to it)

Updated by sawa (Tsuyoshi Sawada) almost 4 years ago Actions #4 [ruby-core:106046]

"font-bold" if root? reads much better than root? ? "font-bold".

Updated by joelb (Joel Blum) almost 4 years ago Actions #5 [ruby-core:106866]

If we adopt this syntax it might be worthwhile to consider JS new colaescing operator which does the same thing, maybe it's better to keep the syntax similar to JS. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator.

So basically just

a ?? b

Updated by nobu (Nobuyoshi Nakada) almost 4 years ago Actions #6 [ruby-core:106889]

?? is a character literal.
As omitting the : and after makes the syntax value conflicting of course, I don't think this is acceptable.

Actions

Also available in: PDF Atom