Skip to content

Commit 20442b9

Browse files
author
zzak
committed
reapply r40839 [Fixes rubyGH-316]
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@40906 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
1 parent b8b26d0 commit 20442b9

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

lib/forwardable.rb

+24-14
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,40 @@
1919
# #record_number(), which simply calls #[] on the <tt>@records</tt>
2020
# array, like this:
2121
#
22+
# require 'forwardable'
23+
#
2224
# class RecordCollection
25+
# attr_accessor :records
2326
# extend Forwardable
2427
# def_delegator :@records, :[], :record_number
2528
# end
2629
#
30+
# We can use the lookup method like so:
31+
#
32+
# r = RecordCollection.new
33+
# r.records = [4,5,6]
34+
# r.record_number(0) # => 4
35+
#
2736
# Further, if you wish to provide the methods #size, #<<, and #map,
2837
# all of which delegate to @records, this is how you can do it:
2938
#
30-
# class RecordCollection
31-
# # extend Forwardable, but we did that above
39+
# class RecordCollection # re-open RecordCollection class
3240
# def_delegators :@records, :size, :<<, :map
3341
# end
34-
# f = Foo.new
35-
# f.printf ...
36-
# f.gets
37-
# f.content_at(1)
38-
#
39-
# If the object isn't a Module and Class, You can too extend Forwardable
40-
# module.
41-
#
42-
# printer = String.new
43-
# printer.extend Forwardable # prepare object for delegation
44-
# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
45-
# printer.puts "Howdy!"
42+
#
43+
# r = RecordCollection.new
44+
# r.records = [1,2,3]
45+
# r.record_number(0) # => 1
46+
# r.size # => 3
47+
# r << 4 # => [1, 2, 3, 4]
48+
# r.map { |x| x * 2 } # => [2, 4, 6, 8]
49+
#
50+
# You can even extend regular objects with Forwardable.
51+
#
52+
# my_hash = Hash.new
53+
# my_hash.extend Forwardable # prepare object for delegation
54+
# my_hash.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
55+
# my_hash.puts "Howdy!"
4656
#
4757
# == Another example
4858
#

0 commit comments

Comments
 (0)