0
我有下一個代碼:執行塊錯誤
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': Invalid attribute (RuntimeError) from ./example_19.rb:23:in
'
爲什麼以及如何解決?
這不正是你想要的嗎?您正在驗證該年齡≥18,然後您使用10歲,並且引發異常。什麼令人驚訝? – 2012-03-20 08:27:33