Forum: Ruby ruby conditional operator ? :

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ad68180beef0a583cd6c438de0fd4738?d=identicon&s=25 Yaxm Yaxm (yaxm)
on 2007-04-28 10:51
Hi,
in java, I can use ? : shorthand operators to ensure s is assigned to
some value.
String s = s == null ? "" : s;

Is there similar shorthand operator in Ruby?

Thanks.
Yaxm
1c0cd550766a3ee3e4a9c495926e4603?d=identicon&s=25 John Joyce (Guest)
on 2007-04-28 10:58
(Received via mailing list)
On Apr 28, 2007, at 5:51 PM, Yaxm Yaxm wrote:

> --
> Posted via http://www.ruby-forum.com/.
>

The same old ternary operator is in Ruby as in most languages these
days.
  ?  :
so...

conditional_statement ? true_result : false_result
97550977337c9f0a0e1a9553e55bfaa0?d=identicon&s=25 Jano Svitok (Guest)
on 2007-04-28 11:24
(Received via mailing list)
On 4/28/07, John Joyce <dangerwillrobinsondanger@gmail.com> wrote:
> > Thanks.
>
> conditional_statement ? true_result : false_result

For assigning default value ||= is usually used (for non-logic values)

i.e.
@name ||= "Joe"

doesn't work for logic values (will overwrite false)
search google for ruby idioms (e.g.
http://wiki.rubygarden.org/Ruby/page/show/RubyIdioms)

Jano
1c0cd550766a3ee3e4a9c495926e4603?d=identicon&s=25 John Joyce (Guest)
on 2007-04-28 11:33
(Received via mailing list)
On Apr 28, 2007, at 6:23 PM, Jano Svitok wrote:

>> > Is there similar shorthand operator in Ruby?
>>   ?  :
> search google for ruby idioms (e.g.
> http://wiki.rubygarden.org/Ruby/page/show/RubyIdioms)
>
> Jano
>

of course there are many ways to set default values. The Perl slogan
applies to Ruby very well.
This topic is locked and can not be replied to.