Skip to content

Instantly share code, notes, and snippets.

@eliotsykes
Last active March 16, 2017 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliotsykes/ae1b0c32b417e069e11408b99ae67935 to your computer and use it in GitHub Desktop.
Save eliotsykes/ae1b0c32b417e069e11408b99ae67935 to your computer and use it in GitHub Desktop.
Class Variables shared by all instances
# 1. Create a file class_variables.rb with the contents below
# 2. Run the file with `ruby class_variables.rb` in Terminal
# 3. Review the output and the code below and explore why:
#
# - the class variable @@total_results_count correctly counts the number
# of all Result instances.
#
# - the class variable @@errors does not track the errors for
# a single instance, instead it wrongly tracks *all* errors
# for all Result instances.
#
# 4. Note that class variables can be used to track state that is shared
# by all instances of the class (in this case the total count of
# all Result instances).
#
# 5. Note that class variables cannot be used to track state is
# individual to an instance of the class (in this case errors
# should not be shared between different Result instances).
class Result
# There is only one object with this name @@errors,
# and it is shared by all Result instances:
@@errors = []
@@total_results_count = 0
def initialize
@@total_results_count = @@total_results_count + 1
end
def add_error(reason)
@@errors << reason
end
def errors_message
@@errors.join(', ')
end
def total_results_count
@@total_results_count
end
end
r1 = Result.new
puts "Just constructed the 1st instance of Result"
puts "Total results count: #{r1.total_results_count}"
r2 = Result.new
puts "Just constructed a 2nd instance of Result"
puts "Total results count: #{r1.total_results_count}"
r3 = Result.new
puts "Just constructed a 3rd instance of Result"
puts "Total results count: #{r1.total_results_count}"
puts "r1 errors message: '#{r1.errors_message}'"
puts "r2 errors message: '#{r2.errors_message}'"
puts "Add an error to r1 only"
r1.add_error('result 1 has a bad foo')
puts "r1 errors message: '#{r1.errors_message}'"
puts "Why is this printing r1's error message?"
puts "r2 errors message: '#{r2.errors_message}'"
puts "Add an error to r2 only"
r2.add_error('result 2 is missing crucial data')
puts "Why are these lines printing both r1 and r2s error messages combined?"
puts "r1 errors message: '#{r1.errors_message}'"
puts "r2 errors message: '#{r2.errors_message}'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment