ruby - How to understand if unless combination in rails? -
i'm reading official rails 4 guide in section . there conditional statements don't understand . this post helps me understand cases confused following example:
def ensure_login_has_a_value if login.nil? self.login = email unless email.blank? end end
i understand in way : if login.nil?
return true. code self.login = email
executed, if email.blank?
return true . nothing.
however when @ code :
before_create self.name = login.capitalize if name.blank?
i have no idea why if conditional statement there ?
when encounter kind of issue , instead of asking on stackoverflow?
with this:
before_create self.name = login.capitalize if name.blank? end
if this:
before_create self.name = login.capitalize end
then name
overwritten login.capitalize
. instead, want set name equal login if name isn't set. it's saying "the default value name capitalized version of login".
the first bit of code quite confusingly written , bit clumsy. rewrite thus:
def ensure_login_has_a_value if self.login.blank? && !self.email.blank? self.login = self.email end end
which think bit more readable.
Comments
Post a Comment