Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: "&& return" vs "and return"

Tags:

While going through the Rails guide at http://guides.rubyonrails.org/layouts_and_rendering.html#avoiding-double-render-errors , I wrote a test program to test Ruby's && return, and I got this strange behavior:

def test1   puts 'hello' && return   puts 'world' end  def test2   puts 'hello' and return   puts 'world' end 

This is the result output:

irb(main):028:0> test1 => nil irb(main):029:0> test2 hello world => nil 

What accounts for the difference?

like image 923
Spec Avatar asked Sep 22 '16 03:09

Spec


People also ask

What is Ruby is used for?

Ruby is mainly used to build web applications and is useful for other programming projects. It is widely used for building servers and data processing, web scraping, and crawling. The leading framework used to run Ruby is Ruby on Rails, although that's not the only one.

What is special about Ruby?

Ruby is distinguished for its bright red color, being the most famed and fabled red gemstone. Beside for its bright color, it is a most desirable gem due to its hardness, durability, luster, and rarity. Transparent rubies of large sizes are even rarer than Diamonds. Ruby is the red variety of the mineral Corundum.

What kind of language is Ruby?

More specifically, Ruby is a scripting language designed for front- and back-end web development, as well as other similar applications. It's a robust, dynamically typed, object-oriented language, with high-level syntax that makes programming with it feel almost like coding in English.

Why was Ruby created?

Ruby was created by Yukihiro Matsumoto, or "Matz", in Japan in the mid 1990's. It was designed for programmer productivity with the idea that programming should be fun for programmers. It emphasizes the necessity for software to be understood by humans first and computers second.


1 Answers

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.

like image 123
Jack Noble Avatar answered Sep 19 '22 19:09

Jack Noble