Rahul Aich
Rahul Aich

Reputation: 37

Replacing text with Ruby

I am trying to replace a pattern in my json file with Ruby. Input file has:

p={'x': 1534804991, 'y': 0.1}

I want the output:

p={:x=>1534804991, :y=>0.1}

I tried using gsub

p.gsub(''x'',':x=>')
p.gsub("'x'",":x=>")
p.sub!(\w/x\w/, ":x=>")

but it did not work.

Upvotes: 0

Views: 71

Answers (2)

khiav reoy
khiav reoy

Reputation: 1403

I guest what you meant is:

p = File.read('xxx.json')
# => "{'x': 1534804991, 'y': 0.1}" 

puts p
# => {'x': 1534804991, 'y': 0.1}

If so, using gsub like the following would work.

puts p.gsub(/'(\w+)': /, ':\1=>')
# => {:x=>1534804991, :y=>0.1}

Upvotes: 0

Sebastián Palma
Sebastián Palma

Reputation: 33420

I guess the point on what you want is transforming - or getting a new representation of your hash - with its keys as symbols rather than as String as you currently show in your input example.

For doing that transform_keys would work:

hash = {'x': 1534804991, 'y': 0.1}
p hash.transform_keys(&:to_sym) # {:x=>1534804991, :y=>0.1}

If your Ruby version doesn't support transform_keys, you can use each_with_object, or any of the "old" ways:

hash.each_with_object({}) { |(k, v), h| h[k] = v }

In order to change to value of a key in a hash, you must access its elements (key, value), and over there, do the manipulation or the assignation (to a new object).

Upvotes: 3

Related Questions