Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using && Instead Of And

DZone's Guide to

Using && Instead Of And

·
Free Resource
Source: and vs && (double ampersand) in Ruby - Momoro Machine [themomorohoax.com] via Twitter / Fabio Akita: RT @igrigorik: just learne ... [twitter.com]

 
  
Many people seem to prefer using and instead of && in Ruby, as it sounds more like speech.

However, do note that it’s slightly different from using &&. The difference is important enough that I think you should avoid using and.


  
alien = true
speaks_english = false

# 1
alien and speaks_english ? 'hello' : '**silence**'
#=> "**silence**"

# 2
alien && speaks_english ? 'hello' : '**silence**'
#=> "**silence**"

# 3
speaks_english and alien ? 'hello' : '**silence**'
#=> false  # oops

# 4
speaks_english && alien ? 'hello' : '**silence**'
#=> "**silence**"


 

Interestingly enough ...

alien = true
speaks_english = false

# 1
if alien and speaks_english then 'hello' else '**silence**' end
#=> "**silence**"

# 2
if alien && speaks_english then 'hello' else '**silence**' end
#=> "**silence**"

# 3
if speaks_english and alien then 'hello' else '**silence**' end
#=> "**silence**"

# 4
if speaks_english && alien then 'hello' else '**silence**' end
#=> "**silence**"
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}