[RAILS] [Ruby comprehension check] Can you explain what is happening? && and and

I had an interesting question so I shared it in a test format

phenomenon

def ampersand_return
  puts "foo" && return
  puts "bar"
end

def and_return
  puts "foo" and return
  puts "bar"
end

> ampersand_return
=> nil

> and_return
foo
bar
=> nil

Can you explain what's happening?

Answer

As a general rule, the difference between && and ʻand` lies in its priority.

For && return

&& is calculated first and is equivalent to the following

puts ("foo" && return)

Since " foo " is truthy, return on the right side is processed, and the method returns without outputting anything.

ʻAnd return`

puts" foo " is calculated first and is equivalent to

(puts "foo") and return

Since puts returns nil, the right side of ʻandis not processed, both" foo "and" bar "` are output, and the method ends normally.

At the end

Isn't the documentation specified about operators where method call takes precedence, as in the ʻand example? Yo According to [This Stack Overflow Answer](https://stackoverflow.com/a/42077277/3891638), ʻand, ʻor, ʻif, ʻunless, ʻuntil, while, rescue Seems to behave this way

Recommended Posts

[Ruby comprehension check] Can you explain what is happening? && and and
[Ruby] What is true?
Existence check of has_many and belongs_to-optional: What is true?
What you write in C # is written in Ruby like this
What is a Ruby module?
[Ruby] What is an instance?
What is Microservices? And Microservices Frameworks
[Ruby on Rails] What is Bcrypt?
What is a Ruby 2D array?
What you can do with ruby ​​Quick reference teaching materials (for beginners)
[Technical memo] What is "include" in Ruby?
What is Java and Development Environment (MAC)
What is RSA signature verification and why?
[Ruby] What is the slice method? Let's solve the example and understand the difference from slice!
[Ruby] Calculation results between decimal points are different, different, and not what you intended.