# What does the ||= operator mean?

**URL:** <https://www.ruby-forum.com/t/what-does-the-operator-mean/143459>\
**Category:** Rails\
**Created:** [July 18, 2008, 9:01pm UTC](https://www.ruby-forum.com/t/what-does-the-operator-mean/143459 "2008-07-18T21:01:03Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![christoph](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/eb8c5e/32.png) [@christoph](https://www.ruby-forum.com/u/christoph)\
**Post date:** [July 18, 2008, 9:01pm UTC](https://www.ruby-forum.com/t/what-does-the-operator-mean/143459/1 "2008-07-18T21:01:03Z")

</div>

Hi all,  
I hope it’s ok that I ask this question here, I don’t wanted to  
subscribe to two other lists. If I have more questions regarding ruby  
itself I will do this.

I’ve seen the ||= operator several times in codes, screencasts and so  
on, but I don’t know it’s use. Surely this will be no problem for  
nearly every developer here, so thank you in advance.

Greetings  
Christoph

---

<div class="post-metadata">

**Author:** ![christoph](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/eb8c5e/32.png) [@christoph](https://www.ruby-forum.com/u/christoph)\
**Post date:** [July 18, 2008, 9:06pm UTC](https://www.ruby-forum.com/t/what-does-the-operator-mean/143459/2 "2008-07-18T21:06:21Z")

</div>

See:  
[http://www.softiesonrails.com/2007/2/6/ruby-101-for-net-developers-the-s](http://www.softiesonrails.com/2007/2/6/ruby-101-for-net-developers-the-s)  
trange-OR-operator

aka:

[http://is.gd/Xhx](http://is.gd/Xhx)

---

<div class="post-metadata">

**Author:** ![christoph](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/eb8c5e/32.png) [@christoph](https://www.ruby-forum.com/u/christoph)\
**Post date:** [July 18, 2008, 9:09pm UTC](https://www.ruby-forum.com/t/what-does-the-operator-mean/143459/3 "2008-07-18T21:09:51Z")

</div>

Here it is in context

def get\_latest  
@get\_latest ||= Posts.find :all, :limit =\> 10, :order =\> “created\_at  
DESC”  
end

||= means “return what you have already. If you’re nil, then go get a  
value.”  
This is called “menoinizing” and is a nice way to cache values.

Rails actually uses this a lot… when you have Post has\_many :comments,  
the .comments method on an instance of a Post is created and does  
something  
similar:

@comments ||= Comment.find :all, :conditions =\> [“post\_id = ?”, self.id]

This way if you call @post.comments from your controller and then again  
from  
your view, it only hits the db once.

---

<div class="post-metadata">

**Author:** ![christoph](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/eb8c5e/32.png) [@christoph](https://www.ruby-forum.com/u/christoph)\
**Post date:** [July 18, 2008, 9:20pm UTC](https://www.ruby-forum.com/t/what-does-the-operator-mean/143459/4 "2008-07-18T21:20:23Z")

</div>

Thank you both !  
This completely explained my question.

Greetings Christoph
