Skip to content

Instantly share code, notes, and snippets.

@JCallicoat
Created July 8, 2013 06:13
Show Gist options
  • Save JCallicoat/5946565 to your computer and use it in GitHub Desktop.
Save JCallicoat/5946565 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 = []
counter = 0
limit = selector.delete(:__limit)
@hashes.each do |h|
is_match = selector.each do |k,v|
break false unless h[k] == v
end
hashes << h if is_match
counter += 1
break hashes if limit && counter >= limit
end
hashes
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', __limit: 1})
puts '----'
puts i.find_by({name: 'Pat', gender: 'm'})
puts '----'
puts i.find_by({__limit: 3})
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