Skip to content

Instantly share code, notes, and snippets.

@krainboltgreene
Created December 28, 2011 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save krainboltgreene/1529607 to your computer and use it in GitHub Desktop.
Save krainboltgreene/1529607 to your computer and use it in GitHub Desktop.
class Hash
def gather(field = :all, options)
unless options[:in].nil?
values = options[:in].inject(self) do |memo, field|
memo[field]
end.map do |hash|
hash[field] if hash.key? field
end
values.select! { |value| options[:only].call value } if options[:only]
values.reject! { |value| options[:not].call value } if options[:not]
return values
end
end
end
$example_data = { profile:
{ name: "Kurtis Rainbolt-Greene",
age: 24,
friends: [
{ name: "Jason Wilhelm", age: 25 },
{ name: "John Numaker", age: 29 },
{ name: "Johnson Reed", age: 14 }
]
}
}
conditions = ->(value) { value.include? "John" }
$example_data.gather :name, in: [:profile, :friends], only: conditions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment