我上课了枚举。
如何仅限制3个对象的访问权限?
class My
include Enumerable
def initialize(*s)
@s = s
end
def each(&blok)
@s.each(&blok)
end
end
这没关系,只有字符串和整数以及我的
b = Array.new(3)
m = My.new
my = MySuperObject("normal","slowly",1,m)
这不行,双,数组
my = MySuperObject(1.5,"ok",b,m)
答案 0 :(得分:2)
你的意思是这样吗?
require 'forwardable'
class MySuperObject
extend Forwardable
def_delegators :@target, *Enumerable.instance_methods
def initialize(*args)
if args.any? { |arg| ![String,Fixnum].include?(arg.class) }
#alternatively as @tadman pointed out you could use
#args.all? { |arg| arg.is_a?(String) || arg.is_a?(Fixnum) }
raise ArgumentError, 'Must be a String or Integer'
else
#what ever you need to do here
@target = args
end
end
end
然后
MySuperObject.new(12,"String")
#=> #<MySuperObject:0x2c1e568>
MySuperObject.new(12.4,"String")
#ArgumentError: Must be a String or Integer
关于这不是一个没有这样的东西的Enumerable类的抱怨吗(Enumerable是一些类中包含的模块)我已经更新了我的答案,将所有可枚举方法委托给@target
。
MySuperObject.instance_methods.sort - Object.methods
#=> [:all?, :any?, :chunk, :collect, :collect_concat, :count, :cycle,
:detect, :drop, :drop_while, :each_cons, :each_entry,
:each_slice, :each_with_index, :each_with_object, :entries,
:find, :find_all,:find_index, :first, :flat_map, :grep,
:group_by, :inject, :map, :max, :max_by, :member?, :min,
:min_by, :minmax, :minmax_by, :none?, :one?, :partition,:reduce,
:reject, :reverse_each, :select, :slice_before, :sort, :sort_by,
:take, :take_while, :to_a, :zip]
请注意rubyists喜欢鸭子打字和限制输入这样做应该有充分的理由这样做,因为它打破了这个概念。