问题
Is it true that in most cases, in Ruby, it is best to use &&
, ||
instead of and
, or
, unless it is some special situations.
I think one of Ruby's design principles is to have least surprises as possible, so using and
, or or
actually have some surprises... such as and
not having a higher precedence than or
, while &&
has a higher precedence than ||
.
So I think in most cases, use &&
, ||
. In know in some special situations, it may require using and
, or
, but I think if those are intermixed with &&
, ||
, sooner or later it may create bugs when your coworkers who started in Ruby not so long ago need to edit your code.
回答1:
Yes. Relying on and
and or
for boolean logic is a good way to introduce subtle bugs into your application.
They do have a place, though. They are a safe and readable option when used as control flow operators.
redirect_to root_url and return
I basically felt the way you did until I read this excellent blog post.
回答2:
The book 'The Ruby Programming Language' (David Flanagan & Yukihiro Matsumoto) gives two reasons to use 'and'.
readability:
if x > 0 and y > 0 and not defined? d then d = Math.sqrt(x*x +y*y) end
make good use of the lower precedence:
if a = get_from_db(x) and b = get_from_db(y) then do_stuff_with_true_values(a, b) end
(code adapted by me) The last one just wouldn't work with '&&'.
Personally, I use 'and' and 'or' combined with parentheses in case of doubt, for readability.-
回答3:
It's because and
, or
& not
have lower precedence than &&
, ||
and !
.
Why? Because it stems from Perl. Larry Wall being a linguist wanted the following to work:
open my $fh, "<", $filename or die $!;
If you replace the or
with ||
then that statement would be parsed like this:
open my $fh, "<", ($filename || die $!);
Which is not good!
So for languages like Perl & Ruby where parenthesis are often optional then this was the solution. Otherwise you would need to write:
open( my $fh, "<", $filename ) || die $!;
See perlop "Logical Not, And, or, Defined or, and Exclusive Or && Logical operators in Perl and Ruby for the full shake down.
/I3az/
来源:https://stackoverflow.com/questions/3826112/in-ruby-should-we-always-use-instead-of-and-or-unless-for-speci