How do I convert a Ruby hash so that all of its keys are symbols?

后端 未结 15 1843
不思量自难忘°
不思量自难忘° 2020-12-04 19:01

I have a Ruby hash which looks like:

{ \"id\" => \"123\", \"name\" => \"test\" }

I would like to convert it to:

{ :id         


        
15条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 19:42

    I'm partial to:

    irb
    ruby-1.9.2-p290 :001 > hash = {"apple" => "banana", "coconut" => "domino"}
    {
          "apple" => "banana",
        "coconut" => "domino"
    }
    ruby-1.9.2-p290 :002 > hash.inject({}){ |h, (n,v)| h[n.to_sym] = v; h }
    {
          :apple => "banana",
        :coconut => "domino"
    }
    

    This works because we're iterating over the hash and building a new one on the fly. It isn't recursive, but you could figure that out from looking at some of the other answers.

    hash.inject({}){ |h, (n,v)| h[n.to_sym] = v; h }
    

提交回复
热议问题