-
Notifications
You must be signed in to change notification settings - Fork 0
/
ways_to_def_methods.rb
65 lines (53 loc) · 995 Bytes
/
ways_to_def_methods.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
animal = 'dog'
# define singleton speak() method
=begin
def animal.speak
puts "#{capitalize} says Woof!"
end
=end
# define method in animal's eigenclass (same as above, really)
=begin
class << animal
def speak
puts "#{self.capitalize} says Woof!"
end
end
=end
# through define_method
=begin
define_method(:speak) do
puts "#{self.capitalize} says Woof!"
end
=end
# add the method to animal's instance
=begin
animal.instance_eval do
def speak
puts "#{capitalize} says Woof!"
end
end
=end
# through an included module
=begin
module Speaker
def speak
puts "#{capitalize} says Woof!"
end
end
animal.class.class_eval { include Speaker }
=end
# through an extended module (ok, I'm cheating a bit!)
=begin
module Speaker
def self.extended(base)
base.class_eval { include InstanceMethods }
end
module InstanceMethods
def speak
puts "#{capitalize} says Woof!"
end
end
end
animal.class.class_eval { extend Speaker }
=end
animal.speak #=> 'Dog says Woof!'