Skip to content

Instantly share code, notes, and snippets.

@justincampbell
Last active August 29, 2015 14:07
Show Gist options
  • Save justincampbell/818b2d030dd07d94b958 to your computer and use it in GitHub Desktop.
Save justincampbell/818b2d030dd07d94b958 to your computer and use it in GitHub Desktop.
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