Skip to content

Instantly share code, notes, and snippets.

@JCallicoat
Created July 8, 2013 06:17
Show Gist options
  • Save JCallicoat/5946591 to your computer and use it in GitHub Desktop.
Save JCallicoat/5946591 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class ArrayWithHashes
def initialize(hashes)
@hashes = hashes
end
def find_by(selector)
@hashes.select do |h|
selector.each do |k,v|
break false unless h[k] == v
end
end
end
end
hashes = [
{ id: 1, name: 'Pat', gender: 'f' },
{ id: 2, name: 'Pat', gender: 'm' },
{ id: 3, name: 'Steve', gender: 'm' },
{ id: 4, name: 'Sue', gender: 'f' },
]
i = ArrayWithHashes.new(hashes)
puts i.find_by({name: 'Pat'})
puts '----'
puts i.find_by({name: 'Pat', gender: 'm'})
puts '----'
puts i.find_by({})
puts '----'
puts i.find_by({id: 5})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment