Ruby 执行块错误

Ruby 执行块错误,ruby,Ruby,我有下一个代码: class Class def attr_checked(attribute, &validation) define_method "#{attribute}=" do |value| raise 'Invalid attribute' unless validation.call(value) instance_variable_set("@#{attr

我有下一个代码:

class Class
    def attr_checked(attribute, &validation)
        define_method "#{attribute}=" do |value|            
            raise 'Invalid attribute' unless validation.call(value)         
            instance_variable_set("@#{attribute}", value)
        end

        define_method attribute do
            instance_variable_get "@#{attribute}"
        end
    end
end

class Person
    attr_checked :age do |v|
        v >= 18
    end
end

bob = Person.new
bob.age = 10
p bob.age
以及执行时的错误消息:

.\example_19.rb./example_19.rb:4:in
block in attr_checked':
无效属性(运行时错误)
from./example_19.rb:23:in
'


为什么以及如何修复它?

这实际上正是您的代码所要求的

只有当块的计算结果为true时,attr_checked方法才会返回true。仅当年龄大于或等于18时,您的块才会返回true

attr_checked :age do |v|
        v >= 18
end
当设置age=10时,此块返回false,并根据此行返回“Invalid Attribute”(无效属性)错误:

raise 'Invalid attribute' unless validation.call(value)

这不正是你想要的吗?您正在验证年龄是否大于等于18岁,然后使用10岁,并引发异常。有什么奇怪的?