Be careful with Array(...)

A popular ruby idiom I keep stumbling upon is
def do_some_thing_for(values)
values = Array(values)
values.each { ... }
end

The intent is to allow the user to pass in arrays as well as scalar values, since
Array("foo") == ["foo"]
Array(["foo", "bar"]) == ["foo", "bar"]

But Array() actually calls to_a on its arguments, which may not always do what you expect. For example
Array("foo \n bar") == ["foo \n", "bar"]

Tobias Kraze Over 13 years ago