Project

General

Profile

Actions

Feature #11734

closed

Improved ternary operator

Feature #11734: Improved ternary operator

Added by Anonymous almost 10 years ago. Updated almost 10 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:71650]

Description

In ternary operator it would be nice to be able to pass expression result from condition into value_if_true/value_if_false in such way:

some_long_expression ? &.to_s : 'foobar'
where & refers to some_long_expression

Instead of doing:
some_long_expression ? some_long_expression.to_s : 'foobar'

or:
result = some_very_very_long_expression result ? result.to_s : 'foobar'

Updated by Hanmac (Hans Mackowiak) almost 10 years ago Actions #1 [ruby-core:71651]

why not:

(x = some_long_expression) ? x.to_s : 'foobar'

Updated by danielpclark (Daniel P. Clark) almost 10 years ago Actions #2 [ruby-core:71662]

& is associated more with proc. I think _ would be closer to the kind of thing you're looking for.

some_long_expression = :baz
_ ? _.to_s : 'foobar'
# => "baz"

Although I tried in-lining it with a semicolon and found that the _ feature only works off of the previous' lines results. So the following won't work.

:buzz; _ ? _.to_s : 'foobar'
# => "foobar"

And this doesn't work

x = 4
:fiz ? _.to_s : 'foobar'
# => "4"

So if you don't mind putting your ternary operation on the next line you can just use _

Updated by Hanmac (Hans Mackowiak) almost 10 years ago Actions #3 [ruby-core:71677]

@Daniel: _ with previous line result is a feature of IRB and PRY not ruby itself

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

Maybe some_long_expression&.to_s || 'foobar' ?

Updated by Anonymous almost 10 years ago Actions #5 [ruby-core:71680]

Hans Mackowiak wrote:

why not:

(x = some_long_expression) ? x.to_s : 'foobar'

think it's not good. Ruby 2.2.3p173 shows warning:

warning: found = in conditional, should be ==

Updated by Anonymous almost 10 years ago Actions #6 [ruby-core:71681]

Nobuyoshi Nakada wrote:

Maybe some_long_expression&.to_s || 'foobar' ?

@Nobuyoshi, thanx! safe navigation from 2.3 solves such tasks.

Updated by Hanmac (Hans Mackowiak) almost 10 years ago Actions #7 [ruby-core:71683]

Yurko Bregey wrote:

Hans Mackowiak wrote:

why not:

(x = some_long_expression) ? x.to_s : 'foobar'

think it's not good. Ruby 2.2.3p173 shows warning:

warning: found = in conditional, should be ==

you might did something wrong because on "ruby 2.3.0dev (2015-11-25 trunk 52749) [x86_64-linux]" it doesn't show any warning for me

Updated by ko1 (Koichi Sasada) almost 10 years ago Actions #8 [ruby-core:71892]

  • Status changed from Open to Closed
Actions

Also available in: PDF Atom