For instances of the class I'm writing (ActiveRecord model), I would like to be able to overload assignments as follows:
m.rank['foo'] = 1
m.rank['bar'] = 2
In other words, I do not want the numbers to be written into the actual hash @rank
, but I would like the setter method with 'foo'
and to be called as its parameters 1
.
A naive way to get this functionality is to define set_rank(key, rank)
and get_rank(key)
, but the syntax is not very cloying. For better syntax, you can define a helper class that defines []
both []=
and the method rank
returns an instance of this class.
Is there an established template to write this in concise form? Or is it a bad idea in the first place, and I should just use set_rank
and get_rank
?
source
share