Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使警告在ruby中只出现一次?_Ruby_Warnings - Fatal编程技术网

如何使警告在ruby中只出现一次?

如何使警告在ruby中只出现一次?,ruby,warnings,Ruby,Warnings,是否可以让ruby只发出一次警告,而不是多次 class SoylentGreen def eat warn "Algae harvesting not implemented. Soylent green is people!" end end 5.times do soylent_green = SoylentGreen.new soylent_green.eat end 产生 Algae harvesting not implemented. Soylent g

是否可以让ruby只发出一次警告,而不是多次

class SoylentGreen
  def eat
    warn "Algae harvesting not implemented. Soylent green is people!"
  end
end

5.times do
  soylent_green = SoylentGreen.new
  soylent_green.eat
end
产生

Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
而理想情况下,我希望它只发生一次

我没有使用rails,可以访问ruby 1.8和1.9


可供选择的方法包括编写自己的警告系统(只包含像这样的故意警告),或者将警告放在
SoylentGreen#eat
之外(即使未调用该方法也会显示该警告)。

您不能这样做吗? 我相信2个符号构成了一个静态变量

class SoylentGreen
  @@warned = false
  def eat
    if not @@warned then
       @@warned = true
       warn "Algae harvesting not implemented. Soylent green is people!"
    end
  end
end

基于混沌的答案

class SoylentGreen
  def eat
    warn_once "Algae harvesting not implemented. Soylent green is people!"
  end
  def warn_once(msg)
    @@warned||=false
    if not @@warned then
       @@warned = true
       warn msg
    end
  end
end
gem隐藏重复的警告:

require 'warnings'

def danger!
  warn "Fire in the disco!"
end

danger!
danger!

Warnings.grep(/fire/)
# => [...]

Warnings.from('foo/bar.rb')
# => [...]

Warnings.from_method('danger!')
# => [...]

exit
#
# Warnings:
#
#   fire in the disco!
#      lib/foo/bar.rb:42

在这个例子中,如果它在每个循环周期中创建一个新的类实例,那么这是行不通的。如果你想沿着这个路径走,你可以使用一个类变量。是的,我必须查一下。我没有用过Ruby。@Earlz-不确定,我当然不值得投赞成票,但我绝对不值得投反对票。