Last active
August 29, 2015 14:00
-
-
Save FrancoB411/11256918 to your computer and use it in GitHub Desktop.
Hash transform composing functions
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
| # setup data | |
| data1 = {1 => %W{ A B C D E} , 2 => %W{ A B C D E }, 3 => %W{ A B C D E }, 4 => %W{ A B C D E } } | |
| list = data1[1] | |
| def swap_list_values_to_keys(key, list) | |
| list.reduce({}) { |a, value| a.merge({key => value.downcase}.invert) } | |
| end | |
| # p swap_list_values_to_keys(1, list) | |
| # => {"a"=>1, "b"=>1, "c"=>1, "d"=>1, "e"=>1} | |
| # builds the new array by reducing over the previous method. | |
| def transform(hash) | |
| hash.each_pair.reduce([]) do |a, pair| | |
| key = pair.first | |
| list = pair.last | |
| a << (swap_list_values_to_keys(key, list)) | |
| end | |
| end | |
| # p transform(data1) | |
| # => [{"a"=>1, "b"=>1, "c"=>1, "d"=>1, "e"=>1}, {"a"=>2, "b"=>2, "c"=>2, "d"=>2, "e"=>2}, {"a"=>3, "b"=>3, "c"=>3, "d"=>3, "e"=>3}, {"a"=>4, "b"=>4, "c"=>4, "d"=>4, "e"=>4}] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment