I find my self repeating things a lot when I create classes in ruby, often I will end up with something similar to the following:
class Foo
attr_reader :bar_0,
:bar_1,
.
.
.
:bar_n
def initialize( bar_0 = something,
bar_1 = something,
.
.
.
bar_n = something)
@bar_0 = bar_0
@bar_1 = bar_1
.
.
.
@bar_n = bar_n
end
end
Does ruby employ a shortcut for more efficiently implementing something like this?
Judging from the way the question is phrased, you should probably rethink the design of your classes. However, Ruby provides an interesting way to quickly create classes with
attr_accessors (not readers). Here’s a simple example:Of course this is a normal class and you can add all the methods you want (and use getters and setters instead of instance variables, e.g.
varfor the getter andself.var = foofor the setter).If you really don’t want the writers, make them private or
undefthem.All of the above doesn’t help with the tons of assignments in
initializeof course, but then one wonders if you really want to many constructor arguments or if maybe you just have one hash argument and merge that into a default hash.