Skip to content

Instantly share code, notes, and snippets.

@pricees
Created April 16, 2014 16:34
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 pricees/10903828 to your computer and use it in GitHub Desktop.
Save pricees/10903828 to your computer and use it in GitHub Desktop.
Filtering array structs by attributes
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