Last active
August 29, 2015 14:07
-
-
Save justincampbell/818b2d030dd07d94b958 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
Thing = Struct.new(:name) | |
things = [ | |
Thing.new("PlayStation"), | |
Thing.new("Xbox") | |
] # => [#<struct Thing name="PlayStation">, #<struct Thing name="Xbox">] | |
things.find { |thing| thing.name == "PlayStation" } # => #<struct Thing name="PlayStation"> | |
people = [ | |
{ name: "Justin" }, | |
{ 'name' => "Dave" } | |
] | |
people.find { |person| person[:name] == "Justin" } # => {:name=>"Justin"} | |
people.find { |person| person['name'] == "Dave" } # => {"name"=>"Dave"} | |
module Enumerable | |
def find_by(field, value) | |
find { |item| | |
if item.respond_to?(:key?) && item.key?(field) | |
item[field] == value | |
elsif item.respond_to?(field) | |
item.public_send(field) == value | |
else | |
false | |
end | |
} | |
end | |
end | |
things.find_by(:name, "PlayStation") # => #<struct Thing name="PlayStation"> | |
people.find_by(:name, "Justin") # => {:name=>"Justin"} | |
people.find_by('name', "Dave") # => {"name"=>"Dave"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment