Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Using conditional assignment in Ruby (See related posts)

Use conditional assignment when you want a fail safe method to reference a variable's value. In other words if the variable didn't previously contain a value then it will be initialised with one.

a = 'crazy'
a ||= 'attentive'
puts 'my current mood is ' + a

=> my current mood is crazy

a ||= 'attentive'
puts 'my current mood is ' + a

=> my current mood is attentive

References:
- Ruby Programming/Syntax/Operators [wikibooks.org]
- DABlog A short-circuit (||=) edge case [rubypal.com]

You need to create an account or log in to post comments to this site.


Click here to browse all 7284 code snippets

Related Posts