Created
November 5, 2014 11:55
-
-
Save crguezl/6455bb73968254cf9cd9 to your computer and use it in GitHub Desktop.
Delegation in Ruby with DelegateClass.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'delegate' | |
class Set2 < DelegateClass(Array) | |
attr_accessor :sep | |
attr_reader :a | |
protected :a | |
def initialize(*a) | |
@sep = ', ' | |
@a = a.uniq.sort | |
super(@a) | |
end | |
def to_s | |
@a.join(@sep) | |
end | |
# delegated | |
#def length | |
# @a.length | |
#end | |
alias cardinal length | |
# delegated | |
#def include?(x) | |
# @a.include? x | |
#end | |
end | |
if __FILE__ == $0 | |
x = Set2.new(1, 2, 3, 3, 4) | |
puts "x = {#{x}}" | |
puts "x.length = #{x.length}" # x.length = 4 | |
puts "x.cardinal = #{x.cardinal}" # x.cardinal = 4 | |
puts "x includes 2 = #{x.include? 2}" # x includes 2 = true | |
puts "x includes 8 = #{x.include? 8}" # x includes 8 = false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment