Ruby, class attribute with limited range
I have been working with Ruby for three days. I am trying to set a default in the way shown below, for #happiness. i need #happiness to have a range of 0-10, cannot be less than zero or more than ten. Thanks in advance.
class Person
attr_reader :name
attr_accessor :bank_account, :happiness={value > 11}
def initialize(name)
@name = name
@bank_account = 25
@happiness = 8
end
end
If you need a writer method that performs some validation, then you have to write a writer method which performs that validation. For example, something like this:
class Person
attr_reader :name, :happiness
attr_accessor :bank_account
def initialize(name)
@name = name
@bank_account = 25
@happiness = 8
end
def happiness=(value)
raise ArgumentError, "`happiness` needs to be between 0 and 10, but you supplied `#{value}`" unless 0..10 === value
@happiness = value
end
end