Possible Duplicate:
What does ||= (or equals) mean in Ruby?
Out on the internet I’ve seen the following syntax in Ruby/Rails:
user ||= User.new
I’m a newbie and I can’t parse this. Can someone explain to me what the “||=” operator does?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If
useris already set this does nothing, otherwise it will assign a newUserobject (created withUser.new).According to David A. Black, author of “The Well-Grounded Rubyist”:
For some added details, here’s the relevant part of parse.y:
NEW_OP_ASGN_ORis defined innode.h:NEW_NODElooks like this:Looking for
NODE_OP_ASGN_ORleads tocompile.c, where the interesting part looks like this:I think this is more than I ever wanted to know about assignment in Ruby, but it was rather entertaining to look this up.