In Ruby, we should always use "&&", "||" instead of "and", "or", if only for special situations?

Is it true that in most cases in Ruby is best to use &&, ||instead and, orif it is not a special situation.

I think that one of the principles of Ruby design should have the least surprises, so using andor ordoes have some surprises ... for example and, not having a higher priority than or, but &&a higher priority than ||.

So I think that in most cases, use &&, ||. In some special situations, it may be necessary to use and, orbut I think that if they mix with &&, ||sooner or later it can create errors if your employees who started working in Ruby need to edit the code for so long.

+5
source share
3 answers

Yes. Building on andand orfor logical logic, this is a good way to introduce subtle errors into your application.

They have a place. They are a safe and readable option when used as control flow operators.

redirect_to root_url and return

, , .

+7

" Ruby" ( ) "".

  • :

    if x > 0 and y > 0 and not defined? d then d = Math.sqrt(x*x +y*y) end

  • :

    if a = get_from_db(x) and b = get_from_db(y) then do_stuff_with_true_values(a, b) end

(, ). , '& &'.

"" "" , .

+7

, and, or not , &&, || !.

? Perl. , , , :

open my $fh, "<", $filename or die $!;

or ||, :

open my $fh, "<", ($filename || die $!);

!

, , Perl Ruby, , . :

open( my $fh, "<", $filename ) || die $!;

. perlop " , , , , & Perl Ruby .

/I3az/

+2

All Articles