In Ruby, how do you set a variable to a certain value if it is not already defined, and leave the current value if it is already defined?
Share
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.
While
x ||= valueis a way to say “if x contains a falsey value, including nil (which is implicit in this construct if x is not defined because it appears on the left hand side of the assignment), assign value to x”, it does just that.It is roughly equivalent to the following. (However,
x ||= valuewill not throw aNameErrorlike this code may and it will always assign a value toxas this code does not — the point is to seex ||= valueworks the same for any falsey value in x, including the “default”nilvalue):To see if the variable has truly not been assigned a value, use the
defined?method:However, in almost every case, using
defined?is code smell. Be careful with power. Do the sensible thing: give variables values before trying to use them 🙂Happy coding.