-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod_missing_actions_array.rb
More file actions
62 lines (52 loc) · 1.01 KB
/
method_missing_actions_array.rb
File metadata and controls
62 lines (52 loc) · 1.01 KB
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
MSGS =
{
:dance => 'is dancing',
:poo => 'is a smelly doggy!',
:laugh => 'finds this hilarious!'
}
class Dog
attr_accessor :actions
def initialize(name)
@name = name
@actions = []
end
def can(*actions)
actions.each do |a|
@actions << a unless @actions.include?(a)
end
end
def method_missing(name, *args, &block)
if @actions.include?(name)
"#{@name} #{MSGS[name]}"
else
"#{@name} doesn't understand #{name}"
end
end
end
lassie, fido, stimpy = %w[Lassie Fido Stimpy].collect{|name| Dog.new(name)}
lassie.can :dance, :poo, :laugh
fido.can :poo
stimpy.can :dance
p lassie.actions
p lassie.dance
p lassie.poo
p lassie.laugh
puts
p fido.dance
p fido.poo
p fido.laugh
puts
p stimpy.dance
p stimpy.poo
p stimpy.laugh
=begin OUTPUT
"Lassie is dancing"
"Lassie is a smelly doggy!"
"Lassie finds this hilarious!"
"Fido doesn't understand dance"
"Fido is a smelly doggy!"
"Fido doesn't understand laugh"
"Stimpy is dancing"
"Stimpy doesn't understand poo"
"Stimpy doesn't understand laugh"
=end