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

P

Philip Müller

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
 
S

Sebastian Hungerecker

Philip said:
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
 
S

Suraj Kurapati

Sebastian said:
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
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top