Search code examples
ruby-on-railsrubyruby-on-rails-4

Ruby on Rails write Hash to file without : and => values


I have a hash in Ruby on Rails app, which needs to be written in file in below format -

{emp_id:15, emp_name:"Test", emp_sal:1800, emp_currency:"USD"}

But I am able to print it in file in below format -

{:emp_id=>15, :emp_name=>"Test", :emp_sal=>1800, :emp_currency=>"USD"}

Is there a way we can remove : of symbol and replace => with : while writing hash to file?

Thanks!


Solution

  • As I said in comments, you have to do this manually. Use hash.map to get key/value pairs and format them accordingly, join using commas, then add the curlies around the result. I use #to_json as a shortcut to add quotes to strings but not to integers.

    hash = {emp_id:15, emp_name:"Test", emp_sal:1800, emp_currency:"USD"}
    
    require 'json'
    result = '{' + hash.map { |k, v| "#{k}:#{v.to_json}" }.join(', ') + '}'
    
    puts result
    # => {emp_id:15, emp_name:"Test", emp_sal:1800, emp_currency:"USD"}
    

    Note that this only works on a single level. If you have nesting, a recursive function will be needed.