Skip to content

Instantly share code, notes, and snippets.

@myitcv
Created March 1, 2013 03:27
Show Gist options
  • Save myitcv/5062274 to your computer and use it in GitHub Desktop.
Save myitcv/5062274 to your computer and use it in GitHub Desktop.
Take a string that contains colon separated lval:rval pairs, produce a hash that collects the rvals for the lvals
# Take a string that contains colon separated lval:rval pairs
# Produce a hash that collects the rvals for the lvals. E.g.
#
# "Fruit:orangeSize:largeQuantity:5Fruit:Apple"
#
# when considered with the lvals of:
#
# %w(Fruit: Size: Quantity: Fresh:)
#
# results in:
#
# {"Fruit:"=>["orange","Apple"], "Size:"=>["large"], "Quantity:"=>["5"], "Fresh:"=>[]}
#
# input
string = "Fruit:orangeSize:largeQuantity:5Fruit:Apple"
# lvals
lvals = %w(Fruit: Size: Quantity: Fresh:)
# Array to hold our "progress"; will ultimately end up with all the rvals
progress = [string]
# Result hash
result = {}
lvals.each { |split|
# reduce by the split
progress.map!{ |item| item.split(split) }
# we only want 'matches' - i.e. where the split result is > 1
# > 1 because there could be multiple occurences of the lhs
result[split] = progress.select{ |item| item.length > 1 }.map{ |item| item[1..-1] }.flatten
# flatten progress and remove the empty strings (these are no use)
# all other strings need to be preserved (we can't tell whether
# we have reduced enough)
progress.flatten!
progress.delete_if { |item| item.empty? }
# We need to go back over previous processed splits and reduce
# them by the current split; this is where this becomes an n^2
# problem...
result.keys.each { |doner|
result[doner].map!{ |item|
item.split(split).first
}
}
}
puts result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment