Using the ruby #inject method

Public, Ruby General

harrylevine

Created: Jun 16, 2016     Updated: Jun 16, 2016


I had this method to start with:

NON_DEDUCTIBLE_REASONS = ['Jury Duty', 'Bereavement']


def self.attendance_status_ids
  ids = []

  NON_DEDUCTIBLE_REASONS.each do |reason|
    ids << AttendanceStatus.find_by_name(reason.to_s.titleize).try(:id)
  end

  ids
end

And a coworker recommended two things:

  1. The returned ID's array may contain nil values
  2. Try using #inject instead of #each

After reading the Building an Array section of this article, here is the refactored method, using the #inject method:

def self.attendance_status_ids
  NON_DEDUCTIBLE_REASONS.inject([]) do |result, reason|
    attendance_id = AttendanceStatus.find_by_name(reason.to_s.titleize).try(:id)

    result << attendance_id if attendance_id.present?
    result
  end
end