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

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Using conditional assignment in Ruby

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.

   1  
   2  a = 'crazy'
   3  a ||= 'attentive'
   4  puts 'my current mood is ' + a

=> my current mood is crazy

   1  
   2  a ||= 'attentive'
   3  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]
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS