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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)