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

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

Philip Müller wrote:

a and b

=> b

?

I would expect it to return true.

The pseudo-code for and basically looks like this:
a and b =
  if a: b
  else: a
This means that if a or b evaluate to a something that counts as false, then
the whole expression will also evaluate to something that counts as false.
And if neither of them do, then the whole expression will evaluate to
something that counts as true. So for if-conditions etc. the expression will
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 boolean
b) there are quite a few cases where returning a/b is more meaningful and/or
useful than just returning true/false (though that's more the case for "or"
than "end". Example: foo = ARGV[0] or default_value).

HTH,
Sebastian

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

···

On Fri, 17 Apr 2009 17:25:37 +0200, Sebastian Hungerecker <sepp2k@googlemail.com> wrote:

Example: foo = ARGV[0] or default_value).

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-forum.com/\.

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

···

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++.