Skip to content

Instantly share code, notes, and snippets.

@fabioyamate
Created June 26, 2013 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabioyamate/5864768 to your computer and use it in GitHub Desktop.
Save fabioyamate/5864768 to your computer and use it in GitHub Desktop.
reduce application
# the common thinking when you are transforming some data to a non-nil value is use map
a = { foo: 'bar', bar: 'baz' }
[:foo, :bar, :baz, :foobar].map { |k| a[k] }
# => ['bar', 'baz', nil, nil]
# to drop nil cases
[:foo, :bar, :baz, :foobar].map { |k| a[k] }.compact
# => ['bar', 'baz']
[:foo, :bar, :baz, :foobar].reduce([]) do |l, k|
l << a[k] if a.has_key?(k)
l
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment