Created
June 12, 2020 08:12
-
-
Save nnzo/1f9da2d83c260ff7d12191d4975974cc to your computer and use it in GitHub Desktop.
Convert a ruby hash to and from a string/key
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
| class ::Hash | |
| # via https://stackoverflow.com/a/25835016/2257038 | |
| def stringify_keys | |
| h = self.map do |k,v| | |
| v_str = if v.instance_of? Hash | |
| v.stringify_keys | |
| else | |
| v | |
| end | |
| [k.to_s, v_str] | |
| end | |
| Hash[h] | |
| end | |
| # via https://stackoverflow.com/a/25835016/2257038 | |
| def symbol_keys | |
| h = self.map do |k,v| | |
| v_sym = if v.instance_of? Hash | |
| v.symbol_keys | |
| else | |
| v | |
| end | |
| [k.to_sym, v_sym] | |
| end | |
| Hash[h] | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment