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…)
I’d like to point out that there is already a builtin method to do what you want! It’s called
Array(). The question to ask yourself is: what happens to classes that are convertible to arrays (like0..42)?I feel that most Rubyist would expect that they’d be converted. So:
You will get the same results, for example: