How to change hash keys from `Symbol`s to `String`s?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







46















I am using Ruby on Rails 3.2.2 and I would like to "easily" / "quickly" change hash keys from Symbols to Strings. That is, from {:one => "Value 1", :two => "Value 2", ...} to {"one" => "Value 1", "two" => "Value 2", ...}.



How can I make that by using less code as possible?










share|improve this question




















  • 5





    If you used HashWithIndifferentAccess instead of a hash, then that would be done automatically for you.

    – Mark Thomas
    May 11 '12 at 10:46


















46















I am using Ruby on Rails 3.2.2 and I would like to "easily" / "quickly" change hash keys from Symbols to Strings. That is, from {:one => "Value 1", :two => "Value 2", ...} to {"one" => "Value 1", "two" => "Value 2", ...}.



How can I make that by using less code as possible?










share|improve this question




















  • 5





    If you used HashWithIndifferentAccess instead of a hash, then that would be done automatically for you.

    – Mark Thomas
    May 11 '12 at 10:46














46












46








46


9






I am using Ruby on Rails 3.2.2 and I would like to "easily" / "quickly" change hash keys from Symbols to Strings. That is, from {:one => "Value 1", :two => "Value 2", ...} to {"one" => "Value 1", "two" => "Value 2", ...}.



How can I make that by using less code as possible?










share|improve this question
















I am using Ruby on Rails 3.2.2 and I would like to "easily" / "quickly" change hash keys from Symbols to Strings. That is, from {:one => "Value 1", :two => "Value 2", ...} to {"one" => "Value 1", "two" => "Value 2", ...}.



How can I make that by using less code as possible?







ruby-on-rails ruby ruby-on-rails-3 hash






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 11 '12 at 10:28







user12882

















asked May 11 '12 at 10:20









user12882user12882

1,90393050




1,90393050








  • 5





    If you used HashWithIndifferentAccess instead of a hash, then that would be done automatically for you.

    – Mark Thomas
    May 11 '12 at 10:46














  • 5





    If you used HashWithIndifferentAccess instead of a hash, then that would be done automatically for you.

    – Mark Thomas
    May 11 '12 at 10:46








5




5





If you used HashWithIndifferentAccess instead of a hash, then that would be done automatically for you.

– Mark Thomas
May 11 '12 at 10:46





If you used HashWithIndifferentAccess instead of a hash, then that would be done automatically for you.

– Mark Thomas
May 11 '12 at 10:46












7 Answers
7






active

oldest

votes


















65














simply call stringify_keys (or stringify_keys!)



http://apidock.com/rails/Hash/stringify_keys






share|improve this answer



















  • 5





    Be careful with this one.. it does not work recursively.

    – baash05
    Apr 8 '13 at 3:12






  • 15





    deep_stringify_keys is recursive, but I believe it's only in Rails 4: apidock.com/rails/v4.0.2/Hash/deep_stringify_keys

    – Romain Paulus
    Feb 21 '14 at 23:49











  • Thanks @RomainPaulus! that helped!

    – Dorian
    Mar 16 '15 at 19:21



















16














Use stringify_keys/stringify_keys! methods of the Hash class.



You can also use some_hash.with_indifferent_access to return a Hash instance where your key can be specified as symbols or as strings with no difference.






share|improve this answer































    10
















    stringify_keys is nice, but only available in Rails.
    Here's how I would do it in a single line, with zero dependencies:



    new_hash = Hash[your_hash.collect{|k,v| [k.to_s, v]}]


    This works on Ruby 1.8.7 and up.
    If you are working with Ruby 2.1, you can do:



    new_hash = a.collect{|k,v| [k.to_s, v]}.to_h


    Note that this solution is not recursive, nor will it handle "duplicate" keys properly. eg. if you have :key and also "key" as keys in your hash, the last one will take precedence and overwrite the first one.






    share|improve this answer































      5














      stringify_keys from rails



      http://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys



      hash = { name: 'Rob', age: '28' }
      hash.stringify_keys
      # => { "name" => "Rob", "age" => "28" }





      share|improve this answer































        3














        there is a nice library that does the trick, the library is "facets/hash/rekey"
        and the method is rekey!. Se my example below of how to use it. It is just a copy past of



        > require 'facets/hash/rekey'
        => true
        > a = {:one => "Value 1", :two => "Value 2"}
        => {:one=>"Value 1", :two=>"Value 2"}
        > a.rekey!(&:to_s)
        => {"one"=>"Value 1", "two"=>"Value 2"}
        > a
        => {"one"=>"Value 1", "two"=>"Value 2"}





        share|improve this answer































          2














           new_hash = Hash.new
          your_hash.each{ |k,v| new_hash[k.to_s] = v }


          new_hash will be same as your_hash but with string keys






          share|improve this answer

































            0














            I came here to see if there was something better than:



            JSON.parse(hash.to_json)


            But I think I'll stick with what I have.






            share|improve this answer
























            • Be careful with this strategy as it will also turn any values that are symbols into strings.

              – Tom
              Dec 23 '18 at 9:01












            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10549554%2fhow-to-change-hash-keys-from-symbols-to-strings%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            65














            simply call stringify_keys (or stringify_keys!)



            http://apidock.com/rails/Hash/stringify_keys






            share|improve this answer



















            • 5





              Be careful with this one.. it does not work recursively.

              – baash05
              Apr 8 '13 at 3:12






            • 15





              deep_stringify_keys is recursive, but I believe it's only in Rails 4: apidock.com/rails/v4.0.2/Hash/deep_stringify_keys

              – Romain Paulus
              Feb 21 '14 at 23:49











            • Thanks @RomainPaulus! that helped!

              – Dorian
              Mar 16 '15 at 19:21
















            65














            simply call stringify_keys (or stringify_keys!)



            http://apidock.com/rails/Hash/stringify_keys






            share|improve this answer



















            • 5





              Be careful with this one.. it does not work recursively.

              – baash05
              Apr 8 '13 at 3:12






            • 15





              deep_stringify_keys is recursive, but I believe it's only in Rails 4: apidock.com/rails/v4.0.2/Hash/deep_stringify_keys

              – Romain Paulus
              Feb 21 '14 at 23:49











            • Thanks @RomainPaulus! that helped!

              – Dorian
              Mar 16 '15 at 19:21














            65












            65








            65







            simply call stringify_keys (or stringify_keys!)



            http://apidock.com/rails/Hash/stringify_keys






            share|improve this answer













            simply call stringify_keys (or stringify_keys!)



            http://apidock.com/rails/Hash/stringify_keys







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 11 '12 at 10:31









            Viktor TrónViktor Trón

            7,04224046




            7,04224046








            • 5





              Be careful with this one.. it does not work recursively.

              – baash05
              Apr 8 '13 at 3:12






            • 15





              deep_stringify_keys is recursive, but I believe it's only in Rails 4: apidock.com/rails/v4.0.2/Hash/deep_stringify_keys

              – Romain Paulus
              Feb 21 '14 at 23:49











            • Thanks @RomainPaulus! that helped!

              – Dorian
              Mar 16 '15 at 19:21














            • 5





              Be careful with this one.. it does not work recursively.

              – baash05
              Apr 8 '13 at 3:12






            • 15





              deep_stringify_keys is recursive, but I believe it's only in Rails 4: apidock.com/rails/v4.0.2/Hash/deep_stringify_keys

              – Romain Paulus
              Feb 21 '14 at 23:49











            • Thanks @RomainPaulus! that helped!

              – Dorian
              Mar 16 '15 at 19:21








            5




            5





            Be careful with this one.. it does not work recursively.

            – baash05
            Apr 8 '13 at 3:12





            Be careful with this one.. it does not work recursively.

            – baash05
            Apr 8 '13 at 3:12




            15




            15





            deep_stringify_keys is recursive, but I believe it's only in Rails 4: apidock.com/rails/v4.0.2/Hash/deep_stringify_keys

            – Romain Paulus
            Feb 21 '14 at 23:49





            deep_stringify_keys is recursive, but I believe it's only in Rails 4: apidock.com/rails/v4.0.2/Hash/deep_stringify_keys

            – Romain Paulus
            Feb 21 '14 at 23:49













            Thanks @RomainPaulus! that helped!

            – Dorian
            Mar 16 '15 at 19:21





            Thanks @RomainPaulus! that helped!

            – Dorian
            Mar 16 '15 at 19:21













            16














            Use stringify_keys/stringify_keys! methods of the Hash class.



            You can also use some_hash.with_indifferent_access to return a Hash instance where your key can be specified as symbols or as strings with no difference.






            share|improve this answer




























              16














              Use stringify_keys/stringify_keys! methods of the Hash class.



              You can also use some_hash.with_indifferent_access to return a Hash instance where your key can be specified as symbols or as strings with no difference.






              share|improve this answer


























                16












                16








                16







                Use stringify_keys/stringify_keys! methods of the Hash class.



                You can also use some_hash.with_indifferent_access to return a Hash instance where your key can be specified as symbols or as strings with no difference.






                share|improve this answer













                Use stringify_keys/stringify_keys! methods of the Hash class.



                You can also use some_hash.with_indifferent_access to return a Hash instance where your key can be specified as symbols or as strings with no difference.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered May 11 '12 at 10:30









                jdoejdoe

                14.4k23844




                14.4k23844























                    10
















                    stringify_keys is nice, but only available in Rails.
                    Here's how I would do it in a single line, with zero dependencies:



                    new_hash = Hash[your_hash.collect{|k,v| [k.to_s, v]}]


                    This works on Ruby 1.8.7 and up.
                    If you are working with Ruby 2.1, you can do:



                    new_hash = a.collect{|k,v| [k.to_s, v]}.to_h


                    Note that this solution is not recursive, nor will it handle "duplicate" keys properly. eg. if you have :key and also "key" as keys in your hash, the last one will take precedence and overwrite the first one.






                    share|improve this answer




























                      10
















                      stringify_keys is nice, but only available in Rails.
                      Here's how I would do it in a single line, with zero dependencies:



                      new_hash = Hash[your_hash.collect{|k,v| [k.to_s, v]}]


                      This works on Ruby 1.8.7 and up.
                      If you are working with Ruby 2.1, you can do:



                      new_hash = a.collect{|k,v| [k.to_s, v]}.to_h


                      Note that this solution is not recursive, nor will it handle "duplicate" keys properly. eg. if you have :key and also "key" as keys in your hash, the last one will take precedence and overwrite the first one.






                      share|improve this answer


























                        10












                        10








                        10









                        stringify_keys is nice, but only available in Rails.
                        Here's how I would do it in a single line, with zero dependencies:



                        new_hash = Hash[your_hash.collect{|k,v| [k.to_s, v]}]


                        This works on Ruby 1.8.7 and up.
                        If you are working with Ruby 2.1, you can do:



                        new_hash = a.collect{|k,v| [k.to_s, v]}.to_h


                        Note that this solution is not recursive, nor will it handle "duplicate" keys properly. eg. if you have :key and also "key" as keys in your hash, the last one will take precedence and overwrite the first one.






                        share|improve this answer















                        stringify_keys is nice, but only available in Rails.
                        Here's how I would do it in a single line, with zero dependencies:



                        new_hash = Hash[your_hash.collect{|k,v| [k.to_s, v]}]


                        This works on Ruby 1.8.7 and up.
                        If you are working with Ruby 2.1, you can do:



                        new_hash = a.collect{|k,v| [k.to_s, v]}.to_h


                        Note that this solution is not recursive, nor will it handle "duplicate" keys properly. eg. if you have :key and also "key" as keys in your hash, the last one will take precedence and overwrite the first one.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Apr 29 '16 at 10:47









                        elieli

                        180213




                        180213























                            5














                            stringify_keys from rails



                            http://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys



                            hash = { name: 'Rob', age: '28' }
                            hash.stringify_keys
                            # => { "name" => "Rob", "age" => "28" }





                            share|improve this answer




























                              5














                              stringify_keys from rails



                              http://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys



                              hash = { name: 'Rob', age: '28' }
                              hash.stringify_keys
                              # => { "name" => "Rob", "age" => "28" }





                              share|improve this answer


























                                5












                                5








                                5







                                stringify_keys from rails



                                http://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys



                                hash = { name: 'Rob', age: '28' }
                                hash.stringify_keys
                                # => { "name" => "Rob", "age" => "28" }





                                share|improve this answer













                                stringify_keys from rails



                                http://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys



                                hash = { name: 'Rob', age: '28' }
                                hash.stringify_keys
                                # => { "name" => "Rob", "age" => "28" }






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Apr 23 '14 at 12:12









                                EryEry

                                49155




                                49155























                                    3














                                    there is a nice library that does the trick, the library is "facets/hash/rekey"
                                    and the method is rekey!. Se my example below of how to use it. It is just a copy past of



                                    > require 'facets/hash/rekey'
                                    => true
                                    > a = {:one => "Value 1", :two => "Value 2"}
                                    => {:one=>"Value 1", :two=>"Value 2"}
                                    > a.rekey!(&:to_s)
                                    => {"one"=>"Value 1", "two"=>"Value 2"}
                                    > a
                                    => {"one"=>"Value 1", "two"=>"Value 2"}





                                    share|improve this answer




























                                      3














                                      there is a nice library that does the trick, the library is "facets/hash/rekey"
                                      and the method is rekey!. Se my example below of how to use it. It is just a copy past of



                                      > require 'facets/hash/rekey'
                                      => true
                                      > a = {:one => "Value 1", :two => "Value 2"}
                                      => {:one=>"Value 1", :two=>"Value 2"}
                                      > a.rekey!(&:to_s)
                                      => {"one"=>"Value 1", "two"=>"Value 2"}
                                      > a
                                      => {"one"=>"Value 1", "two"=>"Value 2"}





                                      share|improve this answer


























                                        3












                                        3








                                        3







                                        there is a nice library that does the trick, the library is "facets/hash/rekey"
                                        and the method is rekey!. Se my example below of how to use it. It is just a copy past of



                                        > require 'facets/hash/rekey'
                                        => true
                                        > a = {:one => "Value 1", :two => "Value 2"}
                                        => {:one=>"Value 1", :two=>"Value 2"}
                                        > a.rekey!(&:to_s)
                                        => {"one"=>"Value 1", "two"=>"Value 2"}
                                        > a
                                        => {"one"=>"Value 1", "two"=>"Value 2"}





                                        share|improve this answer













                                        there is a nice library that does the trick, the library is "facets/hash/rekey"
                                        and the method is rekey!. Se my example below of how to use it. It is just a copy past of



                                        > require 'facets/hash/rekey'
                                        => true
                                        > a = {:one => "Value 1", :two => "Value 2"}
                                        => {:one=>"Value 1", :two=>"Value 2"}
                                        > a.rekey!(&:to_s)
                                        => {"one"=>"Value 1", "two"=>"Value 2"}
                                        > a
                                        => {"one"=>"Value 1", "two"=>"Value 2"}






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered May 11 '12 at 10:43









                                        rik.vanmechelenrik.vanmechelen

                                        1,7541423




                                        1,7541423























                                            2














                                             new_hash = Hash.new
                                            your_hash.each{ |k,v| new_hash[k.to_s] = v }


                                            new_hash will be same as your_hash but with string keys






                                            share|improve this answer






























                                              2














                                               new_hash = Hash.new
                                              your_hash.each{ |k,v| new_hash[k.to_s] = v }


                                              new_hash will be same as your_hash but with string keys






                                              share|improve this answer




























                                                2












                                                2








                                                2







                                                 new_hash = Hash.new
                                                your_hash.each{ |k,v| new_hash[k.to_s] = v }


                                                new_hash will be same as your_hash but with string keys






                                                share|improve this answer















                                                 new_hash = Hash.new
                                                your_hash.each{ |k,v| new_hash[k.to_s] = v }


                                                new_hash will be same as your_hash but with string keys







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Sep 26 '18 at 8:34









                                                dotoree

                                                2,73011826




                                                2,73011826










                                                answered May 11 '12 at 10:31









                                                abhasabhas

                                                4,70512251




                                                4,70512251























                                                    0














                                                    I came here to see if there was something better than:



                                                    JSON.parse(hash.to_json)


                                                    But I think I'll stick with what I have.






                                                    share|improve this answer
























                                                    • Be careful with this strategy as it will also turn any values that are symbols into strings.

                                                      – Tom
                                                      Dec 23 '18 at 9:01
















                                                    0














                                                    I came here to see if there was something better than:



                                                    JSON.parse(hash.to_json)


                                                    But I think I'll stick with what I have.






                                                    share|improve this answer
























                                                    • Be careful with this strategy as it will also turn any values that are symbols into strings.

                                                      – Tom
                                                      Dec 23 '18 at 9:01














                                                    0












                                                    0








                                                    0







                                                    I came here to see if there was something better than:



                                                    JSON.parse(hash.to_json)


                                                    But I think I'll stick with what I have.






                                                    share|improve this answer













                                                    I came here to see if there was something better than:



                                                    JSON.parse(hash.to_json)


                                                    But I think I'll stick with what I have.







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Nov 16 '18 at 22:52









                                                    pguardiariopguardiario

                                                    37k1080118




                                                    37k1080118













                                                    • Be careful with this strategy as it will also turn any values that are symbols into strings.

                                                      – Tom
                                                      Dec 23 '18 at 9:01



















                                                    • Be careful with this strategy as it will also turn any values that are symbols into strings.

                                                      – Tom
                                                      Dec 23 '18 at 9:01

















                                                    Be careful with this strategy as it will also turn any values that are symbols into strings.

                                                    – Tom
                                                    Dec 23 '18 at 9:01





                                                    Be careful with this strategy as it will also turn any values that are symbols into strings.

                                                    – Tom
                                                    Dec 23 '18 at 9:01


















                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10549554%2fhow-to-change-hash-keys-from-symbols-to-strings%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Xamarin.iOS Cant Deploy on Iphone

                                                    Glorious Revolution

                                                    Dulmage-Mendelsohn matrix decomposition in Python