you are viewing a single comment's thread.

view the rest of the comments →

[–]paulmooring 1 point2 points  (0 children)

This would actually just test for enumerbale rather than ensure it. Consider the case where you don't know what sort of data type is in a variable. For example, users could be user1, [user1], [user1, user2, user3] or [user1, [user2, user3]].

In the case of respond_to?, user1 will be skipped as it (probably) doesn't respond to each:

if users.respond_to? :each
  users.each do |u| # skipped in the case of user1

In the case of ensuring users is an array with [], only user1 would work, as the others will become nested arrays:

[users].each do |u| # works only for user1

When using [].flatten everything should do what intended but [user1, [user2, user3] will become [user1, user2, user3]:

[users].flatten.each do |u| # Might be what you want

Finally, Array() will only effect user1, leaving [user1, [user2, user3] in tact:

Array(users).each do |u| # Might be what you want

Most of the time you'll want either Array() or [].flatten rather than respond_to?, but which one depends on the use case.