Ruby: && return vs and return
Check out the difference between and
and &&
. In the examples you give the method puts
is called without parens around it's arguments and the difference in precedence changes how it is parsed.
In test 1 &&
has higher precedence than the method call. So what's actually happening is puts('hello' && return)
. Arguments are always evaluated before the methods they're called with -- so we first evaluate 'hello' && return
. Since 'hello'
is truthy the boolean does not short circuit and return
is evaluated. When return we exit the method without doing anything else: so nothing is ever logged and the second line isn't run.
In test 2 and
has a lower precedence than the method call. So what happens is puts('hello') and return
. The puts
method logs what is passed to it and then returns nil
. nil
is a falsey value so the and
expression short circuits and the return
expression is never evaluated. We just move to the second line where puts 'world'
is run.
Can (a== 1 && a ==2 && a==3) ever evaluate to true?
If you take advantage of how ==
works, you could simply create an object with a custom toString
(or valueOf
) function that changes what it returns each time it is used such that it satisfies all three conditions.
const a = { i: 1, toString: function () { return a.i++; }}
if(a == 1 && a == 2 && a == 3) { console.log('Hello World!');}
RSpec redirect_to and return vs. redirect_to && return
As per the Rails guide:
Make sure to use
and return
instead of&& return
because&& return
will not work due to the operator precedence in the Ruby Language.
If you prefer to use &&
, enclose the arguments to render
in parentheses:
redirect_to(root_path) && return
Ruby: how to combine puts and return inside if condition?
Because Ruby reads this line
print "Your number is: #{num}" && return if num > 10
like this
print("Your number is: #{num}" && return) if num > 10
That leads the method to return
before it had the chance to print
anything.
Adding a pair of parenthesis helps Ruby to resolve the desired order:
print("Your number is: #{num}") || return if num > 10
Why does Ruby expression with double ampersand using a return statement cause a syntax error
Side Note
It is worth noting that and
and &&
are not equivalent.
and
is a flow control operator while &&
is a Boolean operator. What is the difference?
One example of the differences, using and
, you can assign values.
value = nil and value / 42
This would fail if you tried it as below
value = nil && value / 42
Original Question 1
Assuming I want to evaluate one-liners with a return statement (similar to a certain > commonly used shell/bash expression), would this be a recommended way to do it, or is there > a more recommended approach?
The way I have always seen this done in Ruby is this:
value if conditional
This will return the value if the conditional is met and nil
otherwise. No need for the return
statement if this is the last command in the function!
If you are using this for an early exit to a function, I prefer using an unless
. For instance...
return unless arguments_are_valid
Original Question 2
foo method causes a syntax error. bar doesn't. Why?
It's a matter of operator precedence. See the example below showing how they are evaluated.
(true && return) false
(true) and (return false)
rails rubocop use && instead of and with render and return
Like a comment under your Post, indeed you don't need to return
here.
However if you still want to use return
and have it following RuboCop style, try wrapping render params with brackets.
render('errors/status_code', layout: 'errors/status_code', status: @error_code) && return
Difference between or and || in Ruby?
It's a matter of operator precedence.
||
has a higher precedence than or
.
So, in between the two you have other operators including ternary (? :
) and assignment (=
) so which one you choose can affect the outcome of statements.
Here's a ruby operator precedence table.
See this question for another example using and
/&&
.
Also, be aware of some nasty things that could happen:
a = false || true #=> true
a #=> true
a = false or true #=> true
a #=> false
Both of the previous two statements evaluate to true
, but the second sets a
to false
since =
precedence is lower than ||
but higher than or
.
is there a ruby one-line return if x ?
is there a ruby one-line “
return if x
” ?
Yes:
return value if condition
I love Ruby :-)
Related Topics
How to Run Ruby 2.0 with Jruby 1.7
How to Find Where a Ruby Method Is Declared
How to Add Child Nodes in Nodeset Using Nokogiri
Ruby: "&& Return" VS "And Return"
Do You Know an Alternative Ctags Generator for Ruby
How to Make Rake Tasks Run Under My Sinantra App/Environment
Ruby on Rails, Paperclip, Amazon Aws S3 & Heroku
Ruby Regex - Gsub Only Captured Group
Make: /Usr/Bin/Mkdir: Command Not Found During 'Gem Install Nokogiri' in Ubuntu 20.04
How to Prevent Pipe Character from Causing a Bad Uri Error in Rails 3/Ruby 1.9.2
Access Node Attributes in Chef Library
Best Way to Group by Date with Mongoid
How to Run Irb.Start in Context of Current Class
Most of My Assets Suddenly Return 404 After a Push to Heroku
Rvm Install: Ruby Installation Error