tags:

views:

44

answers:

2

Is it possible to tell ruby to give a warning only once, rather than multiple times?

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

produces

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!

whereas ideally I'd like it to occur only once.

I'm not using rails, and have access to ruby 1.8 and 1.9.

Alternatives would include writing my own warning system (which'd cover only deliberate warnings like this), or putting the warning outside of SoylentGreen#eat (which'd cause it to be displayed even if the method wasn't called).

A: 

Couldn't you do something like this? I believe the 2 ampersands make a variable static.

class SoylentGreen
  @@warned = false
  def eat
    if not @@warned then
       @@warned = true
       warn "Algae harvesting not implemented. Soylent green is people!"
    end
  end
end
ChaosPandion
For the example case, this wouldn't work given that its creating a new instance of the class each loop cycle.
Amber
You could use a class variable if you wanted to go down this path.
Andrew Grimm
Yeah I had to look that up. I haven't used Ruby.
ChaosPandion
why the downvote?
Earlz
@Earlz - Not sure, I certainly don't deserve an up-vote but I definitely don't deserve a down-vote.
ChaosPandion
+3  A: 

Based on Chaos's answer..

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
Earlz