Skip to content

Instantly share code, notes, and snippets.

@crguezl
Created November 5, 2014 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crguezl/6455bb73968254cf9cd9 to your computer and use it in GitHub Desktop.
Save crguezl/6455bb73968254cf9cd9 to your computer and use it in GitHub Desktop.
Delegation in Ruby with DelegateClass.
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