Skip to content

Instantly share code, notes, and snippets.

@joselo
Created March 4, 2012 03:40
Show Gist options
  • Save joselo/1970562 to your computer and use it in GitHub Desktop.
Save joselo/1970562 to your computer and use it in GitHub Desktop.
Writing readable ruby
# Writing readable ruby
# The bad way
def to_hash
hash = {}
@reports.each do |report|
hash.merge! report.to_hash
end
hash
end
# An approach much better
def to_hash
@reports.inject({}) do |report_hash, report|
report_hash.merge report.to_hash
end
end
# The right way
def to_hash
@reports.map(&:to_hash).reduce({}, :merge)
end
# REFERENCES
# http://highgroove.com/articles/2012/02/28/writing-readable-ruby.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment