Skip to content

Instantly share code, notes, and snippets.

@xn
Forked from krainboltgreene/pathy.rb
Created December 28, 2011 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xn/1530530 to your computer and use it in GitHub Desktop.
Save xn/1530530 to your computer and use it in GitHub Desktop.
class Hash
#this is pseudocode
def locate_and_find_all(nodes*, &block)
enum = self
while !nodes.empty?
node = nodes.pop
if enum.has_key? node
enum = enum[node]
else
raise
end
end
enum.find_all(&block)
end
def gather_values(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_values :name, in: [:profile, :friends], only: conditions
#part of me likes gather_values_of, part of me doesn't
#i'd also just let it accept a block and put the conditions in there
@krainboltgreene
Copy link

Ho ho, I likie.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment