Skip to content

Instantly share code, notes, and snippets.

@jvmvik
Created July 27, 2015 13:08
Show Gist options
  • Save jvmvik/951a68253fe9e6d55669 to your computer and use it in GitHub Desktop.
Save jvmvik/951a68253fe9e6d55669 to your computer and use it in GitHub Desktop.
Example of Grouping with Ruby 2+ by using: group_by, Array, collection, subgroup
# Example of Grouping with Ruby
# features: group_by, Array, collection, subgroup
# Here the collection
# where #{group_name}_#{subgroup0}_#{subgroup1}...
collection = ['AA_A_B_C', 'BB_A_B_C', 'CC_A_B_C', 'AA_A_A_A', 'BB_B_B_B']
# To range allow to convert
# a subgroup to a range
#
# | A = 0:1
# | B = 1:3
# | C = 3:5
#
def to_range(name)
case name
when 'A'
[0,1]
when 'B'
[1,3]
when 'C'
[3,5]
else
raise "Error: #{name} "
end
end
# Group element by startting
grouped = collection.group_by { |it| it[0..2] }
raise 'Expect 3 group' unless grouped.size == 3
# Iterate on the group
grouped.each do |group_name, values|
# Display group name
puts group_name.gsub('_', '')
values.each do |value|
puts '---' # Add spacer between each subgroup
# Display a sub group
value[2..value.size-1].split('_').each { |name|
next if name.size == 0
range = to_range(name) # Map each term
puts "- #{name} : #{range.first}:#{range.last}" # Display the mapping
}
end
puts ''
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment