Last Updated: February 25, 2016
·
704
· sheerun

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