[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

ruby conditional operator ? :

Yaxm Yaxm

4/28/2007 8:51:00 AM

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

--
Posted via http://www.ruby-....

3 Answers

John Joyce

4/28/2007 8:59:00 AM

0


On Apr 28, 2007, at 5:51 PM, Yaxm Yaxm wrote:

> 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
>
> --
> Posted via http://www.ruby-....
>

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

conditional_statement ? true_result : false_result

Jano Svitok

4/28/2007 9:23:00 AM

0

On 4/28/07, John Joyce <dangerwillrobinsondanger@gmail.com> wrote:
>
> On Apr 28, 2007, at 5:51 PM, Yaxm Yaxm wrote:
>
> > 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
> >
> > --
> > Posted via http://www.ruby-....
> >
>
> The same old ternary operator is in Ruby as in most languages these
> days.
> ? :
> so...
>
> 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/...)

Jano

John Joyce

4/28/2007 9:32:00 AM

0


On Apr 28, 2007, at 6:23 PM, Jano Svitok wrote:

> On 4/28/07, John Joyce <dangerwillrobinsondanger@gmail.com> wrote:
>>
>> On Apr 28, 2007, at 5:51 PM, Yaxm Yaxm wrote:
>>
>> > 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
>> >
>> > --
>> > Posted via http://www.ruby-....
>> >
>>
>> The same old ternary operator is in Ruby as in most languages these
>> days.
>> ? :
>> so...
>>
>> 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/...)
>
> Jano
>

of course there are many ways to set default values. The Perl slogan
applies to Ruby very well.