-3

I want to convert from:

{"key1" => "value1","key2" => "value2"}

to

{key1: "value1", key2: "value2"}
sawa
  • 165,429
  • 45
  • 277
  • 381
Manoj Kumar
  • 316
  • 1
  • 7
  • Try to explain what is your goal. Maybe you think this is the path, but it depends of what you wanna do. – lcguida Oct 04 '17 at 09:36

1 Answers1

2

For the moment, you have to do this:

{"key1" => "value1", "key2" => "value2"}
.map{|k, v| [k.to_sym, v]}.to_h
# => {:key1=>"value1", :key2=>"value2"}

Slightly more efficient is:

{"key1" => "value1", "key2" => "value2"}
.each_with_object({}){|(k, v), h| h[k.to_sym] = v}
# => {:key1=>"value1", :key2=>"value2"}

In the near future, Hash#transform_keys will probably become available.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • Thank you quick response. But want to use this into JS as JSON and JS does not support for {:key1=>"value1", :key2=>"value2"} It's accepted only {key1:“value1”, key2: “value2”} and {"key1":“value1”, "key2": “value2”} So looking for these {key1:“value1”, key2: “value2”} OR {"key1":“value1”, "key2": “value2”} – Manoj Kumar Oct 04 '17 at 08:09
  • 1
    This answers the question you have made. If not, you should explain what you're trying to achieve in your question. That way we are capable of advising you if is the correct way. – lcguida Oct 04 '17 at 09:35
  • 1
    current stable is 2.4.2 which includes `transform_keys` and `transform_keys!` as `some_hash.transform_keys!(&:to_sym)`. @ManojKumar `to_json` will handle the conversion for you no work needed. – engineersmnky Oct 04 '17 at 16:46
  • @engineersmnky I mistook the method name, and was also outdated. Thanks for the comment. – sawa Oct 04 '17 at 19:28
  • Thank all, I managed this conversion from js because I want similar as it is same which asked in question. – Manoj Kumar Oct 05 '17 at 05:29