Last active
February 19, 2016 15:47
-
-
Save hauntedhost/279ffb0cb4bd669d9965 to your computer and use it in GitHub Desktop.
mixed map in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
items = { item_name_1: "Great Deal", | |
item_options_2: "blah: 2", | |
item_name_2: "Awesome Deal", | |
item_options_1: "foo: 3", | |
item_quantity_1: "1", | |
item_price_2: "9.99", | |
item_price_1: "9.99", | |
itemCount: "2" } | |
def item_key_index(key) | |
(index = /^item_.+_(\d+$)/.match(key)) && (index[1].to_i - 1) | |
end | |
def clean_key(key) | |
key.to_s.gsub(/_(\d+$)/, '').to_sym | |
end | |
def parsed_items(items) | |
items.reduce([]) do |accum, (key, val)| | |
if index = item_key_index(key) | |
accum[index] ||= {} | |
accum[index][clean_key(key)] = val | |
end | |
accum | |
end | |
end | |
p parsed_items(items) | |
#=> [{:item_name=>"Great Deal", :item_options=>"foo: 3", :item_quantity=>"1", :item_price=>"9.99"}, | |
# {:item_options=>"blah: 2", :item_name=>"Awesome Deal", :item_price=>"9.99"}] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment