Ruby syntax to avoid nil input being returned as zero

Viewed 44

a Rails application has a sanitizing method

def mobile=(value)
  super(value.to_s.gsub(/\s+/, "").to_i) unless value.nil?
end

Yet, when submitting via console the following

User.last.update(mobile: nil)

the record was obviously processed to_i returning a 0

mobile: 0

implying that the syntax unless value.nil? is inappropriate. How should the method be expressed to no fire when the value submitted is nil ?

1 Answers

Because you're only calling super if the value is not nil, that means the value is NOT replaced when the value is nil. So if the value contained 0 then it'll still contain 0 afterwards.

If you want to be able to set the value to nil, you should do...

def mobile=(value)
  super(
    value.nil? ? nil : value.to_s.gsub(/\s+/, "").to_i
       )
end
Related