-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathprivate_data.rb
43 lines (35 loc) · 1.03 KB
/
private_data.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# coding: utf-8
# Private Class Methods in Ruby
# Every object oriented language has a different take on the rules of methods and
# objects and classes, and I cut my teeth on Java, which means that forever and
# ever after I’ll assume everything works like Java. That left me writing code
# like the `Apple` class below that has a private class method, but not really.
# You can still call it.
class Apple
def self.latin_name
binomial_name
end
private
def self.binomial_name
'Malus domestica'
end
end
Apple.latin_name
Apple.binomial_name
# no error, works fine
# There’s a way to make class methods private in Ruby, you just gotta jump
# through some hoops. Err, I mean use the `class << self` syntax. This oddity
# pushes an instance singleton onto the class effectively creating class methods.
class Orange
def self.latin_name
binomial_name
end
class << self
private def binomial_name
'Citrus × sinensis'
end
end
end
Orange.latin_name
Orange.binomial_name
# ERROR!!! you can't call a private method.