如何着色ruby哈希中的一个属性

时间:2017-06-04 00:09:20

标签: ruby colorize text-coloring

我只需要在哈希中着色一个值,比如

require 'colorize'
h = {a: 'a', b: 'b'.colorize(:red), c: 'c'}

h[:b]会返回此

"\e[0;31;49mb\e[0m"

因此puts h[:b]按预期工作,而h.to_sh.inspect则提供此

"{:a=>\"\\e[0;31;49ma\\e[0m\", :b=>\"\\e[0;34;49mb\\e[0m\"}"

如您所见,所有控制序列都已被转义。

由于h在使用puts h时被隐式转换为字符串,所以我在终端中得到的是:

{:a=>"a", :b=>"\e[0;31;49mb\e[0m", :c=>"c"}

没有任何颜色。

如何才能获得正确的彩色输出?

2 个答案:

答案 0 :(得分:0)

如果你没有风格点就可以生活:

def _d(*args)
  result = []
  args.each do |arg|
    if arg.is_a?(Hash)
      temp_string = "{"
      parts = []
      arg.each { |k,v| parts << ":#{k}=>\"#{v}\""}
      temp_string += parts.join(", ")
      temp_string += "}"
      result << temp_string 
    else
     result << "#{arg}"
    end
  end
  puts result.join(" ")
end

点击_d h将返回您期望的输出。

答案 1 :(得分:0)

我找到了一个相当肮脏的解决方案,但它可以解决问题,并且不需要为inspect重新定义Hash

require 'colorize'
h = {a: 'a', b: 'b'.colorize(:red), c: 'c'}
puts eval("\"#{h.to_s.gsub('"', '\"')}\"")