Ruby's ||= (OR/Equals) Explained

I mentioned a million times by now that the new Write.app is being written in Ruby. Ruby is fucking amazing if you’re coming from languages like PHP or Java on the backend. There are so many ways to write your code, the code is so much easier to understand, and its overall a very pleasant experience. One of the cool things about Ruby syntax is the ||= assignment operator. It took me a while to wrap my head around it so I’m posting it here for future reference for myself and whoever else wants to use it.

What it means

The ||= is a way of assigning a value to a variable if that variable has a falsy value. This is useful if you’ve built an app where a method is run on each request. For example, in Write.app, because the backend is a pure data API, I need to validate tokens. So in my case I have a method that gives each client an API token of none exists on each request. I don’t want an existing value overwritten if it already exists but there’s so I use ||= to make sure it only gets set if it has no value already.

Example 1

1
2
3
4
5
a = nil
b = 10

a ||= b
 #=> Returns 10

In this example a = 10 because when we began, a was nil which is a falsy/empty value. The next example shows what happens if your variable is already set.

Example 1

1
2
3
4
5
a = 20
b = 10

a ||= b
 #=> Returns 20

In this example a = 20 because a already had a value when the program started.

In the end, when I ran this in an irb shell and saw a short explanation of it it made total sense and ended up being very simple. Be warned though! There are edge cases having to do with Ruby hashes where this functionality doesn’t work as shown here. I’m not going to go into that right now but if you’re working with hashes and need to use ||= then be careful.

Web development

« Securing API Keys in a Client Side JavaScript App Rails Tricky Error: No implicit conversion from symbol to integer »

Comments