-
Notifications
You must be signed in to change notification settings - Fork 49
/
10_reversing_method.rb
77 lines (61 loc) · 1.44 KB
/
10_reversing_method.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
65
66
67
68
69
70
71
72
73
74
75
76
77
# Reversing Method
# There is an easy solution for the specific case of writing to an
# output stream. I'll put that at the end. First, I'll translate
# literally into Ruby.
# Example 1
class Point
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
def print_on(stream)
x.print_on(stream)
stream.next_put_all(' @ ')
y.print_on(stream)
end
end
# Example 2
class Stream
def print(object)
object.print_on(self)
end
end
class Point
def print_on(stream)
stream.print x
stream.next_put_all ' @ '
stream.print y
end
end
# Of course, Ruby has no such thing as "Stream". It has a conventional
# notion of an 'IO-like' object, but no unifying module along the
# lines of Enumerable or Comparable which is included by all IO-like
# objects. More's the pity.
# We could put this functionality in a module, and include it into
# IO-likes as needed. We'll call it #print_obj since #print is already
# taken by IO-likes.
module ObjectPrinter
def print_obj(object)
object.print_on(self)
end
end
class Point
def print_on(io)
io.print x
io.print ' @ '
io.print y
end
end
$stdout.extend(ObjectPrinter)
p = Point.new(23,32)
p.print_on($stdout)
# However, for the specific case of handling output, Ruby has a
# solution which is concise and functionally equivalent to the
# Smalltalk example:
class Point
def print_on(io)
io << x << ' @ ' << y
end
end
puts # blank line
p.print_on($stdout)