Feature #11734
closed
Improved 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 10 years ago
Updated by danielpclark (Daniel P. Clark) over 10 years ago
& is associated more with proc. I think _ would be closer to the kind of thing you're looking for.
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.
And this doesn't work
So if you don't mind putting your ternary operation on the next line you can just use _
Updated by Hanmac (Hans Mackowiak) over 10 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 10 years ago
Maybe some_long_expression&.to_s || 'foobar' ?
Updated by Anonymous over 10 years ago
Updated by Anonymous over 10 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 10 years ago
Yurko Bregey wrote:
Hans Mackowiak wrote:
why not:
think it's not good. Ruby 2.2.3p173 shows warning:
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 10 years ago
- Status changed from Open to Closed