This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
| Delegating Method Calls to Another Object | ||
|---|---|---|
| Code | Expected | Actual |
require 'delegate' |
An integer represented as an ordinal number (1st, 2nd, 3rd...), as opposed to a cardinal number (1, 2, 3...) Generated by the DelegateClass to have all the methods of the Fixnum class. |
|
class OrdinalNumber < DelegateClass(Fixnum)
def to_s
delegate_s = __getobj__.to_s
check = abs
if check == 11 or check == 12
suffix = "th"
else
case check % 10
when 1 then suffix = "st"
when 2 then suffix = "nd"
else suffix = "th"
end
end
delegate_s + suffix
end
end
4.to_s |
"4" | "4" |
OrdinalNumber.new(4).to_s |
"4th" | "4th" |
OrdinalNumber.new(102).to_s |
"102nd" | "102nd" |
OrdinalNumber.new(11).to_s |
"11th" | "11th" |
OrdinalNumber.new(-21).to_s |
"-21st" | "-21st" |
OrdinalNumber.new(5).succ |
6 | 6 |
OrdinalNumber.new(5) + 6 |
11 | 11 |
OrdinalNumber.new(5) + OrdinalNumber.new(6) |
11 | 11 |
require 'forwardable'
class AppendOnlyArray
extend Forwardable
def initialize
@array = []
end
def_delegator :@array, :<<
end
a = AppendOnlyArray.new
a << 4
a << 5
a.size |
NoMethodError: undefined method `size' for #<AppendOnlyArray:0xb7bf56f4 @array=[4, 5]> ... |
NoMethodError: undefined method `size' for #<AppendOnlyArray:0xb7bf56f4 @array=[4, 5]> from (irb):37 |
class RandomAccessHash
extend Forwardable
def initialize
@delegate_to = {}
end
def_delegators :@delegate_to, :[], "[]="
end
balances_by_account_number = RandomAccessHash.new |
Load balances from a database or something. |
|
balances_by_account_number["101240A"] = 412.60 balances_by_account_number["104918J"] = 10339.94 balances_by_account_number["108826N"] = 293.01 balances_by_account_number["104918J"] |
10339.94 | 10339.94 |
balances_by_account_number.each do |number, balance|
puts "I now know the balance for account #{number}: it's #{balance}"
end |
NoMethodError: undefined method `each' for #<RandomAccessHash:0xb7be7298> ... |
NoMethodError: undefined method `each' for #<RandomAccessHash:0xb7be7298> from (irb):50 |