[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

simple (?) question regarding the "&&" and "and" operators

Philip Müller

4/17/2009 3:07:00 PM

Hi,

why is

a = Something.new
b = Something.new

a and b

=> b

?

I would expect it to return true.
Same thing goes for the && operator

Regards
Philip
4 Answers

Sebastian Hungerecker

4/17/2009 3:26:00 PM

0

Philip M=C3=BCller wrote:
> a and b
>
> =3D> b
>
> ?
>
> I would expect it to return true.


The pseudo-code for and basically looks like this:
a and b =3D
if a: b
else: a
This means that if a or b evaluate to a something that counts as false, the=
n=20
the whole expression will also evaluate to something that counts as false.=
=20
And if neither of them do, then the whole expression will evaluate to=20
something that counts as true. So for if-conditions etc. the expression wil=
l=20
work as expected.
The reason that it returns a/b and not true/false is that
a) there are very few cases where you need the value to be an explicit bool=
ean
b) there are quite a few cases where returning a/b is more meaningful and/o=
r=20
useful than just returning true/false (though that's more the case for "or"=
=20
than "end". Example: foo =3D ARGV[0] or default_value).

HTH,
Sebastian

Philip Müller

4/17/2009 6:48:00 PM

0

On Fri, 17 Apr 2009 17:25:37 +0200, Sebastian Hungerecker
<sepp2k@googlemail.com> wrote:
> Example: foo = ARGV[0] or default_value).

Thanks,
ruby can be different to understand sometimes for someone coming from
c/c++.

Suraj Kurapati

4/17/2009 8:28:00 PM

0

Sebastian Hungerecker wrote:
> foo = ARGV[0] or default_value

Be careful. "or" has low precedence!

irb(main):001:0> default_value = 12
=> 12
irb(main):002:0> foo = ARGV[0] or default_value
=> 12
irb(main):003:0> foo
=> nil
irb(main):004:0> foo = ARGV[0] || default_value
=> 12
irb(main):005:0> foo
=> 12
--
Posted via http://www.ruby-....

Robert Klemme

4/18/2009 7:33:00 AM

0

On 17.04.2009 20:47, Philip Müller wrote:
> On Fri, 17 Apr 2009 17:25:37 +0200, Sebastian Hungerecker
> <sepp2k@googlemail.com> wrote:
>> Example: foo = ARGV[0] or default_value).
>
> Thanks,
> ruby can be different to understand sometimes for someone coming from
> c/c++.

Yes, maybe. But if you get the hang of it you will see how useful this
is. Actually what the expression returns is a value which is "true"
equivalent, i.e. you can do things like

if a && b
puts "both set"
end

But also, and this is where the fact is handy that one of the values is
returned (the first non false and non nil in this case):

x = a || b

In C/C++ you might have to do something like

x = a == NULL ? b : a;

or maybe just

x = a ? a : b;

(My C has become a bit rusty.)

Kind regards

robert