4vunpa
Last Updated: February 25, 2016
·
487
· sheerun
Photo on 08.01.2013 at 04.15

Use Hash#fetch over Hash#[]

Instead of allowing nil objects to be passed around your code, force throwing KeyError exception or provide default argument:

def employees_names
  params[:employees].map(&:name)
end

becomes

def employees_names
  params.fetch(:employees).map(&:name)
rescue KeyError
  []
end

or even

def employees_names
  params.fetch(:employees, []).map(&:name)
end

Reference: Brain Pratt's Blog

Say Thanks
Respond