mkk
mkk

Reputation: 7693

Array method inconsistent behaviour

I encountered weird behaviour of the Array method and I wonder if there is any reason for it? It looks like a bug in Ruby to me:

Array(1)
[1]
Array('')
[""]
Array({})
[] # ???
Array(nil)
[] # ???

when I passed nil or {} to Array, I expected to get an array with one element, instead, I got an empty Array. Note that when I passed an empty string, it correctly (in my opinion) returns an array with one element. Could anyone explain the logic behind this behaviour?

I expect:

Array(nil) # => [nil]
Array({})  # => [{}]

which would be consistent with:

Array('')  # => ['']

Or another reasonable behaviour would be:

Array('')  # => []

which would be 'consistent' with:

Array(nil) # => []
Array({})  # => []

Upvotes: 0

Views: 62

Answers (2)

eiko
eiko

Reputation: 5345

The function Array(x) tries to convert x to an array using the following logic:

  1. Try to convert it implicitly using x.to_ary
  2. Try to convert it explicitly using x.to_a
  3. Convert it by wrapping it in an array, ie [x]

So individual objects dictate the logic for how they are converted to arrays. The reason Array('') is [''] instead of [] is that strings have no to_ary or to_a method, as of ruby 1.9. I believe this change was made because there is no canonical way to convert a string to an array. Do you want it split up by line, by characters? etc.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160171

For hashes the behavior is well-defined: the hash is broken up into key/value pairs, each pair in a "sub"-array. An empty hash has no key/value pairs, so it's an empty array. Little else makes sense; special-casing for an empty object would break the principle of least surprise.

For nil you could argue either way. Since nil isn't anything IMO an empty array makes sense.

Ultimately the answer is because that's what .to_ary and .to_a return. For nil I'd find an empty array more nil-y than an array with a single nil in it. For hashes I think it must be consistent with how non-empty hashes are converted to arrays.

Upvotes: 5

Related Questions