DEV Community

Shivashankar
Shivashankar

Posted on

2 1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay