如何以编程方式格式化Ruby哈希?
编程格式化Ruby哈希为指定风格
方案1:自定义递归格式化函数
由于通用格式化工具(如Rubocop)难以匹配你需要的特定排版风格,你可以写一个递归函数来精准控制哈希和数组的输出格式:
def format_custom_ruby(obj, indent_level = 0) indent = " " * indent_level case obj when Hash lines = ["#{indent}{"] obj.each_with_index do |(key, val), idx| key_str = key.is_a?(Symbol) ? "#{key}:" : "\"#{key}\":" if val.is_a?(Hash) || val.is_a?(Array) # 处理嵌套结构,键和左大括号/中括号同行 nested_first_line = format_custom_ruby(val, indent_level + 1).lines.first.strip lines << "#{indent} #{key_str} #{nested_first_line}" # 添加嵌套结构的剩余行 lines += format_custom_ruby(val, indent_level + 1).lines[1..-1] else # 处理基础类型值 val_str = val.is_a?(String) ? "\"#{val}\"" : val.inspect lines << "#{indent} #{key_str} #{val_str}" end lines[-1] += "," unless idx == obj.size - 1 end lines << "#{indent}}" lines.join("\n") when Array lines = ["#{indent}["] obj.each_with_index do |item, idx| if item.is_a?(Hash) # 数组内的哈希元素单独换行,左大括号缩进 item_lines = format_custom_ruby(item, indent_level + 1).lines lines << item_lines.first lines += item_lines[1..-1] else lines << "#{indent} #{item.inspect}" end lines[-1] += "," unless idx == obj.size - 1 end lines << "#{indent}]" lines.join("\n") else obj.inspect end end # 使用示例 original_hash = { type: "Processors::GroupRows", position: 1, config: {columns: [{strategy: "concat_uniq", local_column: "all_emails", source_column: "email"}, {strategy: "concat_uniq", local_column: "all_phones", source_column: "phone"}, {strategy: "count", local_column: "total_ads", source_column: "_id"}, {strategy: "sum_int", local_column: "total_vacancies", source_column: "vacancies"}], group_by_column: "employer", select_row_columns: [{strategy: "maximum", column_type: "date", filter_column: "modified_at", insert_columns: [{source_column: "*"}]}]} } puts format_custom_ruby(original_hash)
运行这段代码后,输出的格式会完全匹配你需要的样式:每个嵌套哈希的左大括号与键同行,数组内的哈希元素单独占一行且缩进对齐,逗号置于上一个元素末尾后衔接下一个元素的左大括号。
方案2:调整RubyBeautify配置
如果你偏好使用现成工具,可以尝试ruby-beautify gem,通过调整配置接近目标风格:
- 安装gem:
gem install ruby-beautify
- 使用代码调用并配置:
require 'ruby-beautify' original_hash = { # 你的原始哈希内容 } # 配置参数调整格式 formatted_code = RubyBeautify.format( original_hash.inspect, indent: 2, brace_style: "k&r", # 让哈希左大括号与键同行 array_element_line_break: true, # 数组元素换行 hash_element_line_break: true # 哈希键值对换行 ) puts formatted_code
如果输出还有细微差异,可以进一步修改ruby-beautify的配置参数,或者对输出结果做少量字符串替换来完全匹配需求。
内容的提问来源于stack exchange,提问作者hakunin
相关产品推荐
相关产品推荐

