Feature #11734
closedImproved ternary operator
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) over 8 years ago
why not:
(x = some_long_expression) ? x.to_s : 'foobar'
Updated by danielpclark (Daniel P. Clark) over 8 years ago
&
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) over 8 years ago
@daniel (Daniel Cavanagh): _ with previous line result is a feature of IRB and PRY not ruby itself
Updated by nobu (Nobuyoshi Nakada) over 8 years ago
Maybe some_long_expression&.to_s || 'foobar'
?
Updated by Anonymous over 8 years ago
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 over 8 years ago
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) over 8 years ago
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) over 8 years ago
- Status changed from Open to Closed