ruby cookbook -- 10.7检查对象是否具有必需的属性

检查是否具有实例变量
	class Object
	  def must_have_instance_variables(*args)
	    vars = instance_variables.inject({}) { |h,var| h[var] = true; h }
	    args.each do |var|
	      unless vars[var]
	        raise ArgumentError, %{Instance variable "@#{var} not defined"}
	      end
	    end
	  end
	end

检查是否支持调用的方法
	class Object
	  def must_support(*args)
	    args.each do |method|
	      unless respond_to? method
	        raise ArgumentError, %{Must support "#{method}"}
	      end
	    end
	  end
	end

你可能感兴趣的:(Ruby)