我不明白为什么我无法从color.rb调用方法colorize
。
我在课堂上写了include color
但是当我尝试执行脚本时,我在wget
中收到了这个错误:
undefined method `colorize' for #<String:0x00000001152d30>
这是代码:
$LOAD_PATH << './lib'
require 'color'
class Download
include color
def wget(arr)
FileUtils.cd('/mnt/list')
site = "xxxxx"
arr.each do |f|
wget = system("wget #{site}#{f}")
logger.info("wget: #{f}".colorize("blue"))
end
end
end
文件color.rb,方法为colorize
module Color
def colorize(color, options = {})
background = options[:background] || options[:bg] || false
style = options[:style]
offsets = ["gray","red", "green", "yellow", "blue", "magenta", "cyan","white"]
styles = ["normal","bold","dark","italic","underline","xx","xx","underline","xx","strikethrough"]
start = background ? 40 : 30
color_code = start + (offsets.index(color) || 8)
style_code = styles.index(style) || 0
"\e[#{style_code};#{color_code}m#{self}\e[0m"
end
end
答案 0 :(得分:1)
只要您想在colorize
个实例上调用String
方法,就应该monkeypatch String
类:
class String
include Color
end
<{1}}课程中的 include color
字符串无意义。
该代码段可能放在代码中的任何位置,例如: G。在Download
模块定义之后。由于您有如上所示的Color
类monkeypatched,因此您可以在字符串实例上调用String
。总结:
colorize