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 Post
linkedin sharing button Share