DEV Community

loading...
Main Street

Using Ruby Procs to improve readability

ortegacmanuel profile image Manuel Ortega ・1 min read

We always try to avoid adding comments to our code. There may be some exceptions but ideally the code itself should clearly express what it is doing.

In this pursuit of code readability and expressiveness Procs are helpful in many scenarios. For example when we are dealing with a complex logic within a block we want to pass to a method (map, select, etc) from the Enumerable module.

Before

def self.error_messages(errors)      
  errors.map { |e| e.message.split(":")[3].strip rescue "" }.uniq.join(", ")
end
Enter fullscreen mode Exit fullscreen mode

Let's focus on the block { |e| e.message.split(":")[3].strip rescue "" } we are passing to the map method. It is not extremely complex but still getting your head around it could take a while especially if it is the first time to face this code or functionally within an application.

After

def self.error_messages(errors)
  extract_readable_message = proc { |e| e.message.split(":")[3].strip rescue "" }
  errors.map(&extract_readable_message).uniq.join(", ")
end
Enter fullscreen mode Exit fullscreen mode

This second version adding a Proc didn't change what the code does, but now anyone coming to these lines of code will easily understand not only what the code does but also why it does it.

What you think? Do you find this is worth it? Have you ever add a Proc as a way to improve readability?

Discussion (0)

pic
Editor guide