Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created August 27, 2020 05:36
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 havenwood/f1adda013b81f02e6f2985bac3ec75d4 to your computer and use it in GitHub Desktop.
Save havenwood/f1adda013b81f02e6f2985bac3ec75d4 to your computer and use it in GitHub Desktop.
A guess at what old_relik was looking for in #ruby IRC
def recurse_ages(hash, depth: 0, history: [])
hash.flat_map do |key, value|
if value.instance_of?(Hash)
history[depth] = key
method(__method__).call value, depth: depth.succ, history: history
else
[history[0..depth.pred], value]
end
end
end
def folk_by_age(hash)
recurse_ages(hash).each_slice(2).to_h.transform_keys do |pairs|
pairs.each_slice(2).map(&:last)
end
end
def same_generation_and_age(hash)
hash.group_by do |ancestry, age|
[ancestry.size, age]
end.map(&:last).select do |grouped|
grouped.size > 1
end.to_h do |grouped|
[grouped.map(&:first), grouped.first.last]
end
end
lineage = {grandparents:
{grandpa_1:
{age: 58,
parents:
{parent_1: {age: 34, children: {child_1: {age: 12}}},
parent_2: {age: 32, children: {child_2: {age: 11}}}}},
grandpa_2:
{age: 59,
parents:
{parent_3: {age: 31, children: {child_4: {age: 12}}},
parent_4: {age: 32, children: {child_5: {age: 11}}}}}}}
same_generation_and_age folk_by_age lineage
#=> {[[:grandpa_1, :parent_1, :child_1], [:grandpa_2, :parent_3, :child_4]]=>12,
# [[:grandpa_1, :parent_2], [:grandpa_2, :parent_4]]=>32,
# [[:grandpa_1, :parent_2, :child_2], [:grandpa_2, :parent_4, :child_5]]=>11}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment