Kernel#Array takes an argument and tries very hard to convert it into an Array.

Let’s look at some examples:

1
2
3
4
5
Array([1,2,3])                 # => [1,2,3]
Array([]) # => []
Array(nil) # => []
Array({:a => 1, :b => 2}) # => [[:a, 1], [:b, 2]]
Array(1..5) # => [1, 2, 3, 4, 5]

Using Kernel#Array can lead to very forgiving APIs.

Consider following method:

1
2
3
4
5
6
7
8
9

def log_reading(reading_or_readings)
readings = Array(reading_or_readings)
readings.each do |reading|
# A real implementation...

puts "[READING] %3.2f" % reading.to_f
end
end
1
2
3
4
log_reading(3.14)
log_reading([])
log_reading([84.4, 23.8675, 33])
log_reading(nil)
1
2
3
4
[READING] 3.14
[READING] 84.40
[READING] 23.87
[READING] 33.00

Conclusion

Kernel#Array is a go-to tool for coercing inputs into Array form.
I throw Kernel#Array and stop worrying about whether the input arrived in the expected form.