Skip to content

Instantly share code, notes, and snippets.

@fbernier
Last active August 29, 2015 13:56
Show Gist options
  • Save fbernier/8917727 to your computer and use it in GitHub Desktop.
Save fbernier/8917727 to your computer and use it in GitHub Desktop.
Which do you prefer?
# Obviously the second solution is faster or a large collection, but some said the first solution is more readable.
# Which would you use?
result = []
collection.each do |c|
result << some_method(c)
end
result.reject!(&:nil?)
# Versus
result = []
collection.each do |c|
value = some_method(c)
result << value if value
end
@chatgris
Copy link

@fbernier I would say:

collection.each_with_object([]) do |c, result|
  value = some_method(c)
  result << value if value
end

@fbernier
Copy link
Author

@chatgris Yes, that's the best solution IMO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment