Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Alphonse Cuccurullo
Alphonse Cuccurullo
2,513 Points

Can someone explain to me the purpose of conditional assignments?

Can someone give me a useful scenario where conditional assignments are helpful?

1 Answer

Daniel Crews
Daniel Crews
14,008 Points

a ||=b is 'almost' equivalent to a || a = b

If a is falsy (false, nil or undefined) it will set a to the value of b, otherwise it will leave a as is and the right side isn't evaluated.

For example:

a = nil

b = 20

a ||= b

a # => 20

Why? It sets 'a' to a default value if a has no value. Think of it as a || a = "default". Practical example, instantiate a new empty hash b ||= {}, or array c ||= []

It is ALMOST equivalent to a || a = b because a || a=b will throw an error if a is undefined.