
Ruby, does it allow Cartesian product constructors
By: a guest on Feb 23rd, 2012 | syntax:
None | size: 1.06 KB | hits: 31 | expires: Never
class Tuple
include Enumerable; include Comparable
class << self
alias_method :[], :new
def call(length)
class_name = :"Tuple#{length}"
return const_get class_name if const_defined? class_name
const_set class_name, Class.new(self) {
(@length = length).times do |i| define_method :"_#{i+1}" do @ary[i] end end
}
end
end
def to_s; "(#{@ary.join(', ')})" end
def inspect; "#<#{self.class} (#{@ary.map(&:inspect).join(', ')})>" end
def to_a; @ary.dup end
def [](*args) @ary[*args] end
def each(*args, &block) @ary.each(*args, &block) end
def <=>(other)
raise TypeError unless other.is_a? self.class
raise TypeError unless each_with_index.all? {|el, i| other.instance_variable_get(:@ary)[i].instance_of?(el.class) }
map.with_index {|el, i| el <=> other.instance_variable_get(:@ary)[i] }.find(0) {|cmp| !cmp.zero? }
end
def initialize(*args)
raise ArgumentError unless args.length == self.class.instance_variable_get(:@length)
(@ary = args).freeze
end
end
t3 = Tuple.(3)[1, :two, 'three']