# Arrayize! convert any non-array object to an array. Leave any existing array alone.
def arrayize(object)
return [object] unless object.is_a?(Array)
object
end
def arrayize2(object)
Array.new(1) { object }.flatten
end
def enumerize(object)
object.enum_for
end
- Benchmark results
for object being an array already and an object that is a hash
puts Benchmark.measure { 1_000_000.times { |t| arrayize(['blah']) } }
0.460000 0.000000 0.460000 ( 0.458994)
puts Benchmark.measure { 1_000_000.times { |t| arrayize({test: 'blah'}) } }
1.060000 0.010000 1.070000 ( 1.064968)
puts Benchmark.measure { 1_000_000.times { |t| arrayize2(['blah']) } }
2.110000 0.000000 2.110000 ( 2.112629)
puts Benchmark.measure { 1_000_000.times { |t| arrayize2({test: 'blah'}) } }
2.350000 0.010000 2.360000 ( 2.356239)
puts Benchmark.measure { 1_000_000.times { |t| enumerize(['blah']) } }
0.800000 0.000000 0.800000 ( 0.803645)
puts Benchmark.measure { 1_000_000.times { |t| enumerize({test: 'blah'}) } }
1.270000 0.000000 1.270000 ( 1.269319)