[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Order of operations

Jack Christensen

6/9/2005 11:56:00 AM

Just got bit by a little order of operations confusion.

irb(main):012:0> a = nil or 1
=> 1
irb(main):013:0> a
=> nil
irb(main):014:0> a = (nil or 1)
=> 1
irb(main):015:0> a
=> 1

Probably old news to long time rubyists but it surprised me. Is there
any way to get a warning or something when a statement like the above
may not be behaving like you would think?

Jack


3 Answers

Devin Mullins

6/9/2005 12:12:00 PM

0

I doubt this is the answer you're looking for, but if you use || instead
of or, the precedence is different. i.e. a = nil || 1 does what you
think it does.

Devin

Jack Christensen wrote:

> Just got bit by a little order of operations confusion.
>
> irb(main):012:0> a = nil or 1
> => 1
> irb(main):013:0> a
> => nil
> irb(main):014:0> a = (nil or 1)
> => 1
> irb(main):015:0> a
> => 1
>
> Probably old news to long time rubyists but it surprised me. Is there
> any way to get a warning or something when a statement like the above
> may not be behaving like you would think?
>
> Jack
>
>



Robert Klemme

6/9/2005 12:13:00 PM

0

Jack Christensen wrote:
> Just got bit by a little order of operations confusion.
>
> irb(main):012:0> a = nil or 1
> => 1
> irb(main):013:0> a
> => nil
> irb(main):014:0> a = (nil or 1)
> => 1
> irb(main):015:0> a
> => 1

But note:

>> a = nil || 1
=> 1
>> a
=> 1
>>
> Probably old news to long time rubyists but it surprised me. Is there
> any way to get a warning or something when a statement like the above
> may not be behaving like you would think?

No, because Ruby cannot know what you expect. But note that there *are*
warnings:

>> if ( a = 10 )
>> "ja"
>> end
(irb):3: warning: found = in conditional, should be ==
=> "ja"
>>

"or" and "and" have much lower precedence than "||" and "&&" to give you
the choice and for example do things like

arr.empty? and puts "it's empty!"
a > 0 and puts "positive"

Kind regards

robert

Christian Neukirchen

6/9/2005 3:40:00 PM

0

Jack Christensen <jack@jncsoftware.com> writes:

> Just got bit by a little order of operations confusion.
>
> irb(main):012:0> a = nil or 1
> => 1
> irb(main):013:0> a
> => nil
> irb(main):014:0> a = (nil or 1)
> => 1
> irb(main):015:0> a
> => 1
>
> Probably old news to long time rubyists but it surprised me. Is there
> any way to get a warning or something when a statement like the above
> may not be behaving like you would think?
>
> Jack

Not that I know of, but note that "||" is like "or" with different
precedence:

irb(main):001:0> a = nil || 1
=> 1
irb(main):002:0> a
=> 1

--
Christian Neukirchen <chneukirchen@gmail.com> http://chneuk...