Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Ruby Hash#to_s equivalent for the 'new' Hash syntax?

Hash#to_s (alias for inspect) always outputs data in the 1.8 hash style:

{key: "value"}.to_s
=> "{:key=>\"value\"}"

Is there any core method that will serialize it in the 1.9 hash style?

{key: "value"}.to_s
=> "{key: \"value\"}"

I'm using this on known data for code refactoring; and since Ruby tends to have an implementation of everything, I'm hoping I was just looking in the wrong place.

Of course, you could hack it in an ugly fashion

"{" + my_hash.to_a.map{|pair| pair[0].to_s + ": " + pair[1].inspect} * ",\n") + "}"

But I'm hoping there's a core method somewhere that's unit tested and fully correct.

like image 357
Lilith River Avatar asked Feb 05 '14 16:02

Lilith River


1 Answers

This works for me ... and it respects string keys.

{key: "value"}.to_s.gsub(/(:(\w+)\s?=>\s?)/, "\\2: ")
like image 115
pa657 Avatar answered Sep 28 '22 01:09

pa657