首页 > 解决方案 > 如何将 ruby​​ 哈希转换为具有特定格式的字符串

问题描述

这是我要格式化的哈希

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

这是预期的结果

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

到目前为止我有以下代码

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

这给了我这个输出

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

但我仍在努力添加其余部分。有什么想法/建议吗?

标签: ruby

解决方案


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}"

步骤如下。

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可以包含任意数量的符合指定模式的键值对。


推荐阅读