DEV Community

Shivashankar
Shivashankar

Posted on

Using ruby reduce method for refactoring.

Using ruby 'reduce' method for refactoring our frequently used code.

Assume we have Employee class which has more than 20 attributes. We have a method basic_details to fetch the
details of basic 5 predefined attributes value.

Generally using loop, the code will be as follows.

class Employee
  BASIC_FIELDS = ['name', 'age' , 'gender', 'email', 'designation']
  attr_accessor :name, :age, :gender, :education, :email, :designation 
  # + some additional 20 attributes

  # code without refactoring to fetch the basic_details
  def basic_details
    details = {}
    BASIC_FIELDS.each do |attr| 
      details.merge!(attr => send(attr))    
    end
   details
  end
end

We shall use reduce method to refactor the basic_details as follows

class Employee
  BASIC_FIELDS = ['name', 'age' , 'gender', 'email', 'designation']
  attr_accessor :name, :age, :gender, :email, :education, :designation 
  # + some additional 20 attributes

  # code using reduce method
  def basic_details
    BASIC_FIELDS.collect{|attr| {attr => send(attr)} }.reduce({}, :merge)
  end
end

Top comments (0)