Created
April 16, 2014 16:34
-
-
Save pricees/10903828 to your computer and use it in GitHub Desktop.
Filtering array structs by attributes
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
module Where | |
def where(options) | |
cols = options.keys | |
vals = options.values | |
select { |item| item.to_h.values_at(*cols) == vals } | |
end | |
end | |
Array.send :include, Where | |
foo = Struct.new :name, :age | |
ary = 10.times.map { foo.new("foo_#{rand 2}", rand(3)) } | |
p ary | |
# => [#<struct name="foo_1", age=0>, #<struct name="foo_1", age=1>, | |
# #<struct name="foo_0", age=2>, #<struct name="foo_1", age=2>, | |
# #<struct name="foo_0", age=2>, #<struct name="foo_1", age=1>, | |
# #<struct name="foo_0", age=2>, #<struct name="foo_0", age=2>, | |
# #<struct name="foo_1", age=1>, #<struct name="foo_0", age=1>] | |
p ary.where(name: "bar") | |
# => [] | |
p ary.where(name: "foo_1") | |
# => [#<struct name="foo_1", age=0>, #<struct name="foo_1", age=1>, #<struct name="foo_1", age=2>, #<struct name="foo_1", age=1>, #<struct name="foo_1", age=1>] | |
p ary.where(name: "foo_1", age: 1) | |
# => [#<struct name="foo_1", age=1>, #<struct name="foo_1", age=1>, #<struct name="foo_1", age=1>] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment