Be careful with Array(...)

Posted . Visible to the public.

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
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2010-10-05 17:17)