Feature #11734
closed
Improved ternary operator
Added by Anonymous over 8 years ago.
Updated over 8 years ago.
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'
why not:
(x = some_long_expression) ? x.to_s : 'foobar'
&
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 _
Maybe some_long_expression&.to_s || 'foobar'
?
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 ==
Nobuyoshi Nakada wrote:
Maybe some_long_expression&.to_s || 'foobar'
?
@Nobuyoshi, thanx! safe navigation from 2.3 solves such tasks.
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
- Status changed from Open to Closed
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0Like0