Created
October 8, 2015 20:58
-
-
Save RafaelMCarvalho/5be76a7e76ca59a679e4 to your computer and use it in GitHub Desktop.
Simple, but useful, methods to manipulate an array of hashes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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