> my_a = [ n ].to_a unless n.class == "Array"
I think what you were trying to write is:
my_a = n
my_a = [ n ] unless n.class == Array
There is actually a Ruby idiom for this:
my_a = Array(n)
Type 'ri Kernel#Array' for more info.
This is a normal method which just happens to start with a capital
letter, which can be confusing. The Ruby interpreter doesn't confuse
this with a constant (or class name) because it is followed by
parentheses, so it must be a method call.
Another version of your original code would be:
my_a = n.is_a?(Array) ? n : [n]
However such class tests are very rare in idiomatic Ruby. Duck-typing
means you don't care what class an object is, just what methods it
responds to.
Since the only method you are going to call is 'collect', you could
write:
my_a = n.respond_to?(:collect) ? n : [n]
Then the caller could pass in *any* object which has a 'collect' method,
and you would use that. Only if it doesn't would it get wrapped in an
Array.
The benefit here is that you could pass in an Enumerable object (such as
an open file), and you could process its elements as they are read
without having to turn the whole file into an Array first.
But equally reasonable would be to drop the [n] part altogether, and
simply define the method as taking an Enumerable object. It would then
be the caller's responsibility to wrap the object if required.
def double( n )
n.collect {|num| num * 2 }
end
puts "\nTest double([1, 2, 3, 4])"
inttest = double( [1, 2, 3, 4] )
puts "\n#{inttest}\n\n"
puts "\nTest double( [3] )"
inttest = double( [3] )
puts "\n#{inttest}\n\n"
This is what tends to happen in idiomatic ruby - the number of lines of
code becomes extremely small :-)
HTH,
Brian.
--
Posted via http://www.ruby-forum.com/.