1

我只需要对哈希中的一个值进行着色,就像那样

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

没有任何颜色。

我应该怎么做才能获得正确的彩色输出?

4

2 回答 2

0

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

require 'colorize'
h = {a: 'a', b: 'b'.colorize(:red), c: 'c'}
puts eval("\"#{h.to_s.gsub('"', '\"')}\"")
于 2017-06-21T21:42:04.190 回答
0

If you can live without style points:

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

Hitting _d h will return the output you expect.

于 2017-06-04T01:00:44.223 回答