Last active
January 20, 2018 03:45
-
-
Save joebutler2/4eb675b839856724d25bf0a5881caf98 to your computer and use it in GitHub Desktop.
Code samples for the "Private constants in Ruby" article
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CPUOpponent | |
def self.base_points | |
1000 | |
end | |
private_class_method :base_points | |
end | |
puts CPUOpponent.base_points | |
# => NoMethodError: private method ‘base_points’ called for CPUOpponent:Class |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def self.base_points | |
@base_points ||= { easy: 1000, medium: 2000, hard: 3000 } | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CPUOpponent | |
def self.base_points | |
@base_points ||= { easy: 1000, medium: 2000, hard: 3000 } | |
end | |
private_class_method :base_points | |
base_points[:super_hard] = 9001 | |
puts base_points.inspect | |
# => {:medium=>2000, :hard=>3000, :super_hard=>9001, :easy=>1000} | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CPUOpponent | |
def self.base_points | |
@base_points ||= { easy: 1000, medium: 2000, hard: 3000 }.freeze | |
end | |
private_class_method :base_points | |
base_points[:super_hard] = 9001 | |
puts base_points.inspect | |
# => TypeError: can't modify frozen hash | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CPUOpponent | |
def self.base_points | |
@base_points ||= { easy: 1000, medium: 2000, hard: 3000 }.freeze | |
end | |
private_class_method :base_points | |
def calculate_score(bonus_points) | |
base_points = self.class.send(:base_points) | |
bonus_points + base_points[:easy] | |
end | |
end | |
opponent = CPUOpponent.new | |
puts opponent.calculate_score(400) | |
# => 1400 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment