What does the ||= operator mean ?

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

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

aka:

http://is.gd/Xhx

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.

Thank you both ! This completely explained my question.

Greetings Christoph