Tips for writing clean and concise Ruby code

|
Tips for writing clean and concise Ruby code
Photo by AltumCode

Ruby is an elegant programming language. The syntax is simple and easy to read. However, as with every other programming language, there are better ways of writing the same code. Writing verbose code as opposed to concise and clean code can take the shine out of the beautiful language.

The following are some tips on how to write clean and concise Ruby code.

Tip Number 1: Use map instead of each to generate an array of values

  # verbose
  users_arr = []
  users.each do |user|
    users_arr << { name: user.name }
  end
  # concise
  users_arr = users.map { |user| { name: user.name } }

Tip Number 2: Use single variable initialization on value presence check

  # verbose
  country = some_country_method() # returns a country object

  if country.present?
    country_code = country.iso
  else
    country_code = "gh"
  end
# concise - for this to work the default value (when there is no value) must be nil
country_code = if country = some_country_method()
  country.iso
else
  "gh"
end

Tip Number 3: Use concise rescue

 # verbose
def valid_id?
  begin
    data = JSON.parse("some json string that could be invalid")
    data.key?("id")
  rescue JSON::ParserError
    false
  end
end
 # concise
def valid_id?
  data = JSON.parse("some json string that could be invalid")
  data.key?("id")
rescue JSON::ParserError
  false
end

Tip Number 4: Use the single splat operator to destructure an array of exception objects

# less clean
def valid_data?
  data = JSON.parse(open("some url").read).with_indifferent_access
  User.create!(data: data)
  true
rescue JSON::ParserError, Errno::ENOENT, ActiveRecord::RecordInvalid, OpenURI::HTTPError, OpenSSL::SSL::SSLError
  false
end
# cleaner
BAD_DATA_EXCEPTIONS = [
  Errno::ENOENT,
  JSON::ParserError,
  OpenURI::HTTPError,
  OpenSSL::SSL::SSLError,
  ActiveRecord::RecordInvalid,
].freeze

def valid_data?
  data = JSON.parse(open("some url").read).with_indifferent_access
  User.create!(data: data)
  true
rescue *BAD_DATA_EXCEPTIONS
  false
end

Tip Number 5: Use except instead of select to filter unwanted Hash keys

# verbose
hash.select { |k, _| k != "unwanted_key" }
# concise
hash.except(:unwanted_key)
Shares
facebook sharing button Share
twitter sharing button Tweet
linkedin sharing button Share

WE CARE ABOUT YOUR PRIVACY

Manage Settings
Vendors

Vendor Settings

Purposes

Vendors can:

Special Purposes

Vendors can:

  • Ensure security, prevent and detect fraud, and fix errors
  • Deliver and present advertising and content
  • Save and communicate privacy choices

Features

Vendors can:

  • Match and combine data from other data sources
  • Link different devices
  • Identify devices based on information transmitted automatically

Special Features

Vendors can:

Some partners do not ask for your consent to process your data, instead, they rely on their legitimate business interest. Personal data processed includes but is not limited to cookies, IP addresses, and URLs visited. View our list of partners to see the purposes they believe they have a legitimate interest for and object to legitimate interests on a per vendor basis. Manage your settings and object to purposes as a legitimate interest in general.

You can change your settings at any time, including by withdrawing your consent, by clicking on the cog icon in the bottom right hand corner.