In Ruby, should we always use “&&”, “||” instead of “and”, “or” unless for special situations? [closed]

◇◆丶佛笑我妖孽 提交于 2019-12-05 10:58:57

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.

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

draegtun

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!