The Billy Baldwin of Conditional Assignment in Ruby
collectiveidea.com
collectiveidea.com
@value ||= "foo" is more efficient than
@value = @value || "foo"
As it actually evaluates as follows: @value || @value = "foo"
This is especially good when working with hashes, as the left hand side is only evaluated once, not twice. @current_user ?= User.find()
# as opposed to @current_user ||= User.find()
and @summary = excerpt?.squish
# as opposed to @summary &&= excerpt.squish if data["incoming"] is None:
data["incoming"] = "Default value"
...
if data["incoming"]:
data["incoming"] = data["incoming"].strip()
Because of Python's string immutability, there's no point to dodging the assignment; you're still going to incur new string creation anyway.For example this:
some_var &&= replace_var()
some_var ||= initialize_var()
versus a more conventional/idiomatic if: some_var = (some_var) ? replace_var() : initialize_var()
||= turns out to be rather useful as a general assign once operator, but i'm having a hard time justifying use of &&=. That and I find myself after learning Erlang to try to assign only once when possible to make debugging easier.While ||= isn't strictly needed, it makes assigning to class/module variables in a single line easier in general. I'm not sure I agree with the Python "always expand to an if statement" methodology though, it just seems like a bit of unneeded yak shaving. (note: i don't use rails so your post may be specific to web frameworks and I'm off my rocker, if so disregard. >.<)
&&= is less well known than ||=. RTFA for examples.
For the example cited, you could also use ActiveRecord::Dirty
def clean_summary
self.summary = summary.squish if self.summary_changed?
end