Spec Spec - 1 year ago 73
Ruby Question

About ruby && return vs and return

according to rails guide,
i wrote a test program to test ruby && return and i got this strange things.i

def test1
puts 'hello' && return
puts 'world'

def test2
puts 'hello' and return
puts 'world'

this is the result output

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

any one can explain ????

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download