There is a key difference that skips the accepted answer. If you are trying to change the attribute when setting the value , then you should use self[:attribute] .
For example...
def some_attr=(val) self.some_attr = val.downcase
This will not work because it is self-regulation (you will get a "too deep stack" error). Instead, you should assign a value by doing ...
def some_attr=(val) self[:some_attr] = val.downcase end
There is also a named method write_attribute , which performs the same actions as self[:attribute] . Both do what you need, it's a matter of coding style and personal preference. I like write_attribute when the attribute that I actually define is variable, for example.
write_attribute(var, 'some value')
Frank koehl
source share