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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With