Tips for writing clean and concise Ruby code
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.
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 } }
# 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
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
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
except
instead of select
to filter unwanted Hash keys# verbose
hash.select { |k, _| k != "unwanted_key" }
# concise
hash.except(:unwanted_key)
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.