Home > Mobile >  How to convert Hash to string Hash?
How to convert Hash to string Hash?

Time:09-16

Here i have the use case where hash to convert to string hash.

hash = {"make" => "tata", "year" => "2006"}
p hash.to_s

output:

"{\"make\"=>\"tata\", \"year\"=>\"2006\"}"

Expected Output should be in string hash and class should be string:

"{"make"=>"tata", "year"=>"2006"}"

CodePudding user response:

As others have commented, you actually get what you look for just using to_s. What you see when you p the string is the inspect representation if the string itself, one that when put in a code file will be your original string.

If you want an additional proof that the string is what you want, just eval the resulting string:


string = {"a" => "b"}.to_s
=>  "{\"a\"=>\"b\"}"

rebuilt = eval string
=> {"a" => "b"}

rebuilt.class
=> Hash

rebuilt.keys[0].class
=> String

rebuilt.values[0].class
=> String

CodePudding user response:

As @Sergio Tulentsev said, using p or inspect is the cleaner & simpler solution.

hash = {"make" => "tata", "year" => "2006"}
p hash
# => {"make"=>"tata", "year"=>"2006"}
puts hash.inspect
# => {"make"=>"tata", "year"=>"2006"}

If you want to reinvent the wheel, see below


If you don't mind having single quotes instead of double quotes:

hash = {"make" => "tata", "year" => "2006"}

def hash_to_string(hash)
  inner_string = hash.map do |key, value|
    "'#{key}' => '#{value}'"
  end.join(', ')

  '{'   inner_string   '}'
end 

# If you prefer overwriting Hash#to_s method
class Hash
  def to_s
    inner_string = self.map do |key, value|
      "'#{key}' => '#{value}'"
    end.join(', ')

   '{'   inner_string   '}'
  end
end

puts hash_to_string hash
# => {'make' => 'tata', 'year' => '2006'}
puts hash.to_s
# => {'make' => 'tata', 'year' => '2006'}
p hash_to_string hash
# => "{'make' => 'tata', 'year' => '2006'}"
p hash.to_s
# => "{'make' => 'tata', 'year' => '2006'}"

Though when you use puts, " are escaped because the String itself is surrounded by double quotes. Ruby uses double quotes to represent strings

  •  Tags:  
  • ruby
  • Related