Ruby : Special behaviour of If statement

I think code snippet will speak aloud than my words, so please go through the snippet

nil_value = nil
if nil_value.ready?
  p 'humanized string' + nil_value
end
Output:
# undefined method `ready?' for nil:NilClass
nil_value = nil
if nil_value && nil_value.ready?
  p 'humanized string' + nil_value
else
  p 'First expression is false, so skipped second expression'
end
Output:
=> "First expression is false, so skipped second expression"

Note: It only works for ‘&&’ but not ‘||’. In case of ‘or’ it tries to execute both the operands ( Expressions)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s