Read more

Be careful with Array(...)

Tobias Kraze
October 05, 2010Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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"]

Posted by Tobias Kraze to makandra dev (2010-10-05 19:17)