SgtPepper
SgtPepper

Reputation: 468

How to convert a ruby hash into a string with a specific format

This is the hash I'm trying to format

input = {"test_key"=>"test_value", "test_key2"=>"test_value2"}

And this is the expected result

"{\n\t\"test_key\" = \"test_value\";\n\t\"test_key2\" = \"test_value2\";\n}"

I have the following code so far

def format_hash(hash)
  output = ""
  hash.to_s.split(',').each do |k|
    new_string = k + ';'
    new_string.gsub!('=>', ' = ')
    output += new_string
  end
end

which gives me the this output

output = "{\"test_key\" = \"test_value\"; \"test_key2\" = \"test_value2\"};"

But I'm still struggling with adding the rest. Any ideas/suggestions?

Upvotes: 1

Views: 278

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110735

input = {"test_key"=>"test_value", "test_key2"=>"test_value2"}

"{" << input.map { |k,v| "\n\t\"#{k}\" = \"#{v}\"" }.join(';') << ";\n}"
  #=> "{\n\t\"test_key\" = \"test_value\";\n\t\"test_key2\" = \"test_value2\";\n}"

The steps are as follows.

a = input.map { |k,v| "\n\t\"#{k}\" = \"#{v}\"" }
  #=> ["\n\t\"test_key\" = \"test_value\"", "\n\t\"test_key2\" = \"test_value2\""] 
b = a.join(';')
  #=> "\n\t\"test_key\" = \"test_value\";\n\t\"test_key2\" = \"test_value2\""
"{" << b << ";\n}"
  #=> "{\n\t\"test_key\" = \"test_value\";\n\t\"test_key2\" = \"test_value2\";\n}" 

input may contain any number of key-value pairs that adhere to the indicated pattern.

Upvotes: 2

Mike
Mike

Reputation: 1337

One starting point might be to use JSON formatter:

require 'json'
input = {"test_key"=>"test_value", "test_key2"=>"test_value2"}
JSON.pretty_generate(input)

=> "{\n  \"test_key\": \"test_value\",\n  \"test_key2\": \"test_value2\"\n}"

This has some subtle differences, since it looks like you use = as opposed to :. That said, perhaps it's easier to work from this than from what you have.

Working with JSON

JSON.pretty_generate(input).gsub(/:/,' =').gsub(/,(?=\n)/, ';').gsub(/(;\n|\n)\s+/, '\1'+"\t")

=> "{\n\t\"test_key\" = \"test_value\";\n\t\"test_key2\" = \"test_value2\"\n}"

Custom Formatter

Of course you could define your custom formatter:

def formatter(hash)
  output = ""
  output += "{\n\t" 
  output += hash.entries.map{|a| "\"#{a[0]}\" = \"#{a[1]}\"" }.join(";\n\t")
  output += ";\n}"
end

formatter( input )

Upvotes: 1

Related Questions