Created
May 19, 2012 03:24
-
-
Save mungruby/2728855 to your computer and use it in GitHub Desktop.
example of using the inject method
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
#!/usr/bin/env ruby -w | |
# chmod +x inject_0001.rb | |
sclass = Struct.new('Person', :name, :age, :gender) | |
people = [] | |
people << sclass.new("Sue", 20, 'M') | |
people << sclass.new("Sue", 20, 'F') | |
people << sclass.new("Sue", 21, 'M') | |
people << sclass.new("Joe", 20, 'M') | |
class PersonFinder | |
attr_reader :people | |
def initialize people | |
@people = people | |
end | |
def find parms = {} | |
parms.map do |attribute, value| | |
self.public_send("find_by_#{attribute}", value) | |
end.inject {|accumulated_results, results| accumulated_results & results}.first | |
end | |
def find_by_name name | |
people.find_all {|person| person.name == name} | |
end | |
def find_by_age age | |
people.find_all {|person| person.age == age} | |
end | |
def find_by_gender gender | |
people.find_all {|person| person.gender == gender} | |
end | |
end | |
if __FILE__ == $0 | |
p PersonFinder.new(people).find( {name: 'Sue', age: 20, gender: 'M'} ) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment