簡體   English   中英

如何為紅寶石哈希着色一個屬性

[英]How to colorize one attribute in ruby hash

我只需要着色哈希中的一個值,像那樣

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

沒有任何顏色。

如何獲得正確的彩色輸出?

如果您可以沒有風格點地生活:

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將返回您期望的輸出。

我找到了一個很骯臟的解決方案,但是它可以解決問題,不需要重新定義inspect Hash

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM