Skip to content

Instantly share code, notes, and snippets.

@RafaelMCarvalho
Created October 8, 2015 20:58
Show Gist options
  • Save RafaelMCarvalho/5be76a7e76ca59a679e4 to your computer and use it in GitHub Desktop.
Save RafaelMCarvalho/5be76a7e76ca59a679e4 to your computer and use it in GitHub Desktop.
Simple, but useful, methods to manipulate an array of hashes.
class Array
def pluck(key)
map { |h| h[key] }
end
# a = [
# {id: 1, name: 'John' },
# {id: 2, name: 'Doe' },
# {id: 3, name: 'John' },
# { name: 'Doe' }
# ]
#
# a.select_by(name: 'John', id: 1)
# => [{:id=>1, :name=>"John"}]
#
# a.select_by(id: /\d/)
# => [{:id=>1, :name=>"John"}, {:id=>2, :name=>"Doe"}, {:id=>3, :name=>"John"}]
#
def select_by(args)
select do |h|
args.map do |k, v|
v.is_a?(Regexp) ? v === h[k].to_s : v == h[k]
end.all?
end
end
# Similar to #select_by, but using #detect logic
#
def detect_by(args)
detect do |h|
args.map do |k, v|
v.is_a?(Regexp) ? v === h[k].to_s : v == h[k]
end.all?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment