字符串的未定义方法

时间:2014-12-01 13:38:24

标签: ruby-on-rails ruby

我不明白为什么我无法从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 

1 个答案:

答案 0 :(得分:1)

只要您想在colorize个实例上调用String方法,就应该monkeypatch String类:

class String
  include Color
end
<{1}}课程中的

include color字符串无意义。

该代码段可能放在代码中的任何位置,例如: G。在Download模块定义之后。由于您有如上所示的Color类monkeypatched,因此您可以在字符串实例上调用String。总结:

colorize