ruby - 如何将 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\"};"
但我仍在努力添加其余部分。有什么想法/建议吗?
解决方案
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
可以包含任意数量的符合指定模式的键值对。
推荐阅读
- swift - 当 NSSearchField 进入和失去焦点时通知 SwiftUI macOS
- workbox - 如果不使用捆绑器,如何解释 Workbox v5 文档
- reactjs - 我无法启动反应脚本
- c++ - 虚拟继承中有多重继承吗?
- javascript - Javascript:有没有更简洁的方法来提取对象属性?
- python-3.x - 熊猫操作,将多个结果放入 df 列
- python - 问:错误函数 'dict' 对象在 python 中不可调用
- go - 从命名管道读取不会给出任何输出并无限期地阻塞代码
- kubernetes - 如何为 kubelet 指标配置 prometheus 目标
- python - TensorFlow KeyError Input_1