https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators#Logical_Or
The binary "or" operator will return the logical disjunction of its
two operands. It is the same as "||" but with a lower precedence
As I understand it, as || has a higher precedence than "or", the code below will first test if 'b' is true, then 'c', and then if both are false will test 'a'. I would like to witness this but am not sure if my understanding is incorrect, or simply my test.
a = true
b = false
c = false
p a or b || c
==> true #but were b and c checked as expected?
My attempt to test this is as follows..
def atest
a = "string a"
a.include? 'string'
a
end
def btest
b = "string b"
b.include? 'string'
b
end
def ctest
c = "string c"
c.include? 'string'
c
end
puts "#{atest or btest || ctest}"
==> string a
I expected 'string b' to be returned... I'm completely new to programming since a week ago so I'm not sure, is my code wrong or is my understanding of the quote wrong?
edit: Appreciation on its own seems to be discouraged in responses, so I'll hide it here. Cheers for all the answers/further reading/code cleanup, it's clear now where I was going wrong.
In Ruby, &&, and, ||, and or are short-circuit operators:
[...] the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.
In your example:
a or b || c
Ruby evaluates a, sees a truthy value and immediately returns it, without evaluating b || c.
or's lower precedence means that the expression is evaluated as:
a or (b || c)
instead of:
(a or b) || c
Just like
1 + 2 * 3
is evaluated as:
1 + (2 * 3)
because + has lower precedence than *.
But it doesn't change the order of evaluation. 1 is still evaluated before 2 * 3.
Also note that due to or's very low precedence
p a or b || c
is evaluated as:
(p a) or (b || c)
Neither b nor c will ever be printed this way.
Further readings:
Using “and” and “or” in Ruby
How to use Ruby’s English and/or operators without going nuts
Ruby: On The Perl Origins Of “&&” And “||” Versus “and” And “or”.
Sidenote: In your code there are lines that basically do nothing: a.include? 'string' is silently returning truthy, having no impact at all on the running code. These three functions might be rewritten as:
def atest
"string #{__callee__[0]}"
end
alias :btest :atest
alias :ctest :atest
You are confusing operator precedence with normal execution flow. Operator precedence is about what operation to execute in advance when we have two operations applied to the same operand. Otherwise, the execution order is left-to-right. E.g.
a + b * c
is executed as:
a
b
# oh! ambiguity: lookup the precedence table: will do multiplication
c # (otherwise a + b)
*
+
Related
I have a variable that contains either '&&' or '||' and I need to use it in an if statement like so.
operator = '&&'
result = 1===1 operator 2===2
#=> result = 1===1 && 2===2
How can I achieve this?
I have tried using #public_send but to no avail.
Any help would be appreciated.
The && operator is more of a low-level syntax element than & and | which are method calls. That makes it harder to do.
However, there's two ways:
a = true
b = false
c = true
If you want && equivalence:
[ a, b, c ].all?
# => false
[ a, c ].all?
# => true
If you want || equivalence:
[ a, b, c ].any?
# => true
[ a, b ].any?
# => true
[ b ].any?
# => false
You could do it like this:
operator = "&&"
result = eval "1===1 #{operator} 2===2"
does that do what you want?
or if 1===1 is just a placeholder here for some expression, assign the result to a variable, so:
operator = "&&"
a = 1===1
b = 2===2
result = eval "#{a} #{operator} #{b}"
(of course, as commenters have noted, you must pay attention to the security vulnerabilities of eval, e.g. check that the operator variable is either "&&" or "||".)
and if you really want an if statement:
if operator == '&&'
1===1 && 2===2
elsif operator == '||'
1===1 || 2===2
else
# dunno
end
You can use public_send, but even if it were allowed with &&, it would not make sense. Note that E1 && E2 shortcircuits, in that E2 is not evaluated if E1 is already falsy. How could this work with public_send?
If you want to have this effect, you have to give up shortcircuiting, which means that you have to use & and | instead of && and ||. If you insist that your variable operator contains something like '&&', and not, say :& (which would make more sense), you could do a
result = (1===1).public_send(operator[0], 2===2)
to use your example for demonstration.
UPDATE: The comment of tadman to my answer made me think that I should warn you about the following trap: Based on your question, I assumed that the arguments you want to connect with your operator are either true or false. In this case, my solution indeed should work. However, if you they can be just any truey or falsy value of some class X, you need to convert them to true or false, because otherwise, the operator may have a different interpretation (for instance, if you operands happen to be integer). Hence, for some general operand_e1_ and e2, which - as is the general rule in Ruby - are supposed to be interpreted als false if it is either false or nil, and is taken as true otherwise, the safe way to calculate your result would be
result = (!!e1).public_send(operator[0], !!e2)
where !! ensures that the expressions are converted to true and false so that the operators & and | can safely be applied.
This is just fine:
def foo
a or b
end
This is also fine:
def foo
return a || b
end
This returns void value expression:
def foo
return a or b
end
Why? It doesn't even get executed; it fails the syntax check. What does void value expression mean?
return a or b is interpreted as (return a) or b, and so the value of return a is necessary to calculate the value of (return a) or b, but since return never leaves a value in place (because it escapes from that position), it is not designed to return a valid value in the original position. And hence the whole expression is left with (some_void_value) or b, and is stuck. That is what it means.
In "Does `return` have precedence to certain operators in Ruby?" which I asked, Stefan explained in a comment that the or and and are actually control flow operators and should not be used as boolean operators (|| and && respectively).
He also referenced "Using “and” and “or” in Ruby":
and and or originate (like so much of Ruby) in Perl. In Perl, they were largely used to modify control flow, similar to the if and unless statement modifiers. (...)
They provide the following examples:
and
foo = 42 && foo / 2
This will be equivalent to:
foo = (42 && foo) / 2 # => NoMethodError: undefined method `/' for nil:NilClass
The goal is to assign a number to foo and reassign it with half of its value. Thus the and operator is useful here due to its low precedence, it modifies/controls what would be the normal flow of the individual expressions:
foo = 42 and foo / 2 # => 21
It can also be used as a reverse if statement in a loop:
next if widget = widgets.pop
Which is equivalent to:
widget = widgets.pop and next
or
useful for chaining expressions together
If the first expression fails, execute the second one and so on:
foo = get_foo() or raise "Could not find foo!"
It can also be used as a:
reversed unless statement modifier:
raise "Not ready!" unless ready_to_rock?
Which is equivalent to:
ready_to_rock? or raise "Not ready!"
Therefore as sawa explained the a or b expression in:
return a or b
Has lower precedence than return a which, when executed, escapes the current context and does not provide any value (void value). This then triggers the error (repl.it execution):
(repl):1: void value expression
puts return a or b
^~
This answer was made possible due to Stefan comments.
Simply because or has lower precedence than || which means return a will be executed before or b, or b is therefore unreachable
This is just fine:
def foo
a or b
end
This is also fine:
def foo
return a || b
end
This returns void value expression:
def foo
return a or b
end
Why? It doesn't even get executed; it fails the syntax check. What does void value expression mean?
return a or b is interpreted as (return a) or b, and so the value of return a is necessary to calculate the value of (return a) or b, but since return never leaves a value in place (because it escapes from that position), it is not designed to return a valid value in the original position. And hence the whole expression is left with (some_void_value) or b, and is stuck. That is what it means.
In "Does `return` have precedence to certain operators in Ruby?" which I asked, Stefan explained in a comment that the or and and are actually control flow operators and should not be used as boolean operators (|| and && respectively).
He also referenced "Using “and” and “or” in Ruby":
and and or originate (like so much of Ruby) in Perl. In Perl, they were largely used to modify control flow, similar to the if and unless statement modifiers. (...)
They provide the following examples:
and
foo = 42 && foo / 2
This will be equivalent to:
foo = (42 && foo) / 2 # => NoMethodError: undefined method `/' for nil:NilClass
The goal is to assign a number to foo and reassign it with half of its value. Thus the and operator is useful here due to its low precedence, it modifies/controls what would be the normal flow of the individual expressions:
foo = 42 and foo / 2 # => 21
It can also be used as a reverse if statement in a loop:
next if widget = widgets.pop
Which is equivalent to:
widget = widgets.pop and next
or
useful for chaining expressions together
If the first expression fails, execute the second one and so on:
foo = get_foo() or raise "Could not find foo!"
It can also be used as a:
reversed unless statement modifier:
raise "Not ready!" unless ready_to_rock?
Which is equivalent to:
ready_to_rock? or raise "Not ready!"
Therefore as sawa explained the a or b expression in:
return a or b
Has lower precedence than return a which, when executed, escapes the current context and does not provide any value (void value). This then triggers the error (repl.it execution):
(repl):1: void value expression
puts return a or b
^~
This answer was made possible due to Stefan comments.
Simply because or has lower precedence than || which means return a will be executed before or b, or b is therefore unreachable
In Ruby Integer === 5 returns true. Similarly String === "karthik" returns true.
However, 5 === Integer returns false. And "karthik" === String.
Why is the operator not commutative?
The simple answer is: because it doesn't make sense. The relationship the operator describes is not commutative, why should the operator be?
Just look at your own examples: 5 is an Integer. But is Integer a 5? What does that even mean?
=== is the case subsumption operator, and subsumption doesn't commute.
The fact that the case subsumption operator uses equals signs, and that it is usually called the triple equals, threequals or case equality operator is terribly unfortunate since it not only has absolutely nothing to do with equality, but it also does not conform to many of the laws that equality conforms to, such as transitivity and as you mentioned commutativity.
For more of my ranting about === see
What does the === operator do in Ruby?
=== vs. == in Ruby
How does Integer === 3 work?
One very simple reason is that the is_a? relationship for classes just can't be commutative. Consider the case where both operands are classes:
Class === String
This will return true because String.is_a?(Class). However String === Class will return false, because Class.is_a?(String) is false and that is of course as it should be.
Another reason is that the semantics of === depends on its left operand. This has again two reasons: a) In ruby the semantics always depend on the left operand, because the left operand is the receiver of the method call and b) it is useful, so you can use e.g. classes, ranges and regexen in a case statement with the intended semantics.
Many operators are not commutative.
The === is called the "case equality operator" because it is called when branching is a case.
It is nice and useful that:
foo = 42
case foo
when Integer
# branches here
when String
# etc...
end
It would not be very useful if
foo = Integer
case foo
when 42
# would branch here??
when 666
# etc...
end
Note that in Ruby 1.9, the === operator on a Proc/lambda will call that Proc:
divisible_by_three = ->(x){x % 3 == 0}
divisible_by_three === 42 # => true
Again, very useful in a case statement, but not much in the reverse order.
it needs to implement case-when comparisons
It's normal to have non-commutative operators.
/ - % [] . -> ^ << >> < <= > >= && || = += -= ,
And as it happens, === exists in part as the case-when operator. That's rather elaborate in Ruby, and it couldn't be so if it had to be simplified to a commutative op.
Is there a ruby idiom for "If do-this," and "do-this" just as a simple command?
for example, I'm currently doing
object.method ? a.action : nil
to leave the else clause empty, but I feel like there's probably a more idiomatic way of doing this that doesn't involve having to specify a nil at the end. (and alternatively, I feel like taking up multiple lines of code would be wasteful in this case.
As a general rule: you pretty much never need the ternary operator in Ruby. The reason why you need it in C, is because in C if is a statement, so if you want to return a value you have to use the ternary operator, which is an expression.
In Ruby, everything is an expression, there are no statements, which makes the ternary operator pretty much superfluous. You can always replace
cond ? then_branch : else_branch
with
if cond then then_branch else else_branch end
So, in your example:
object.method ? a.action : nil
is equivalent to
if object.method then a.action end
which as #Greg Campbell points out is in turn equivalent to the trailing if modifier form
a.action if object.method
Also, since the boolean operators in Ruby not just return true or false, but the value of the last evaluated expression, you can use them for control flow. This is an idiom imported from Perl, and would look like this:
object.method and a.action
a.action if object.method?
Greg's answer is the best, but for the record, and even more than in C, expressions and statements are equivalent in Ruby, so besides a.action if o.m? you can also do things like:
object.method? && a.action
You can write (a; b; c) if d or even
(a
b
c
) if d
or for that matter: (x; y; z) ? (a; b c) : (d; e; f)
There is no situation in Ruby where only a single statement or expression is allowed...
result = (<expression> && <true value>) || <false value>
value = 1
result = (value == 1 && 'one' ) || 'two'
result #=> 'one'
Explain: value == 1 && 'one' #=> returns last expression result, value is equals 1 so and section will be evaluated, and return 'one'.
value = 0
result = (value == 1 && 'one' ) || 'two'
result #=> 'two'
Explain: value != 1 and 'and' expression will not be evaluated, but instad will be used 'or' expression and it returns 'two'
Another way this can be done on the same line is:
if object.method; a.action end
This is considered bad style by Rubocop because it uses a semicolon to terminate the expression, but I find it more readable in some conditions than tacking on the if statement at the end. It is easier to overlook an if statement at the end and I don't always want to return something if the condition isn't true(as you are forced into with a ternary operator).
You can also be a bit more verbose and rubocop friendly:
if object.method then a.action end