【问题标题】:Undefined method for string未定义的字符串方法
【发布时间】:2015-01-29 12:49:05
【问题描述】:

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

使用colorize方法的文件color.rb

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 

【问题讨论】:

  • 您在 your 类中包含 Color,而不是 String

标签: ruby-on-rails ruby


【解决方案1】:

只要你想在Strings 实例上调用colorize 方法,你应该monkeypatch String 类:

class String
  include Color
end

include color 类中的 include color 字符串毫无意义。

sn-p 可以放在代码中的任何位置,例如。 G。在 Color 模块定义之后。既然你有 String 类如上所示的猴子补丁,你可以在字符串实例上调用 colorize。总结:

module Color
 def colorize(color, options = {})
 ....
 end
end

class String
  include Color
end

puts 'a'.colorize(...) # ⇒ works

【讨论】:

  • 为什么我需要在文件中添加一个类字符串?
  • 谢谢它的工作,但我不明白类字符串
  • 您是否点击了我提供的链接?
猜你喜欢
  • 2014-06-11
  • 2014-06-01
  • 2013-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
相关资源
最近更新 更多