module CheckArrayElement def element_should_be(klasses) unless @klasses.is_a?(Array) @klasses = [klasses] end end def check_class(arg) unless @klasses.include?(arg.class.to_s) raise TypeError end end def push(arg) check_class(arg) super(arg) end alias :<< :push def []=(i, arg) check_class(arg) super(i, arg) end end module CheckHashElement def element_should_be(klasses) unless @klasses.is_a?(Array) @klasses = [klasses] end end def check_class(arg) unless @klasses.include?(arg.class.to_s) raise TypeError end end def store(key, arg) check_class(arg) super(key, arg) end def []=(key, arg) check_class(arg) super(key, arg) end end a = [] a.instance_eval do extend CheckArrayElement element_should_be 'String' end a.push('222') # a.push(222) #<= TypeError a << '444' # a << 444 #<= TypeError a[0] = '111' #a[0] = 111 #<= TypeError p a h = {} h.instance_eval do extend CheckHashElement element_should_be 'String' end h.store('1', '111') # h.store('1', 111) #<= TypeError h['2'] = '222' # h['2'] = 222 #<= TypeError p h