Skip to content

Instantly share code, notes, and snippets.

@kyuden
Last active August 29, 2015 14:02
Show Gist options
  • Save kyuden/e63039d9b49202b0c444 to your computer and use it in GitHub Desktop.
Save kyuden/e63039d9b49202b0c444 to your computer and use it in GitHub Desktop.
collection
numbers = [1, 2, 3, 4, 5, 6]
result1 = []
numbers.each do |num|
result1 << num * 2 if num % 2 == 0
end
p result1 # => [4, 8, 12]
numbers.select{|num| num % 2 == 0 }.map{|num| num * 2 } # => [4, 8, 12]
numbers.inject([]) {|result2, num| result2 << num * 2 if num % 2 == 0; result2 } #=> [4, 8, 12]
numbers.inject([]) {|result2, num| result2.tap {|r| r << num * 2 if num % 2 == 0 } } #=> [4, 8, 12]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment