########Programming Fundamental######## # If it can happen, it will happen. # Control your flow so crap can't happen. class AnythingElse # This is a class to represent AnythingElse other than what # can_happen will understand def initialize # Personified by the text 'anything else' @anything_else = 'anything else' end def to_s # Only has one method, a to_s to insure that we return the text # value of the class return @anything_else end end # if it can happen, it will happen def can_happen(*anything) # I accept any number of arguments.. if anything.length >= 1 # If i get one or more arguments anything.each do |thing| # For each argument i do the following if thing && thing != true # If the argument exists, and it is not true, we cannot understand it # Note, false, nil and blank arguments do not fall into this category # raise an Exception to cause the process to stop. raise "I don't understand " + thing.to_s elsif thing == false # If the argument received is false puts "If it is #{thing} it Cannot Happen" elsif thing == nil # If the argument received is nil puts "If it is nothing it Cannot Exist." else # Otherwise the only option left is that the argument is true puts "If it is #{thing} it Will Happen" end end else # If no arguments are passed. puts "If it is nothing it Cannot Exist" end end # Begin to use the method. Surround with begin/end to insure that you can # rescue exceptions begin can_happen() # Call can_happen with no arguments can_happen(false, nil, true) # Call can_happen with all other valid arguments # Call can_happen with several invalid arguments. can_happen(AnythingElse.new, 'crap', 'can\'t happen', 0, 0.0, 'true') # Any code that you are testing for exceptions needs to be between 'begin' and 'rescue' rescue Exception => e # Catch any Exception that occurs # Print out Exception and stack trace. puts e.inspect print " "+e.backtrace.join("\n ") else # The program completed without any Exceptions puts "I fully understand!" ensure # This will always happen whether there is an error or not. puts "\nYou cannot fool me!" # end of 'begin' block end