Best way to make an attribute always an array?
Posted
by Shadowfirebird
on Stack Overflow
See other posts from Stack Overflow
or by Shadowfirebird
Published on 2010-03-12T10:06:43Z
Indexed on
2010/03/12
10:07 UTC
Read the original article
Hit count: 160
I'm using my MOO project to teach myself Test Driven Design, and it's taking me interesting places. For example, I wrote a test that said an attribute on a particular object should always return an array, so --
t = Thing.new("test")
p t.names #-> ["test"]
t.names = nil
p t.names #-> []
The code I have for this is okay, but it doesn't seem terribly ruby to me:
class Thing
def initialize(names)
self.names = names
end
def names=(n)
n = [] if n.nil?
n = [n] unless n.instance_of?(Array)
@names = n
end
attr_reader :names
end
Is there a more elegant, Ruby-ish way of doing this?
(NB: if anyone wants to tell me why this is a dumb test to write, that would be interesting too...)
© Stack Overflow or respective owner