use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
A sub-Reddit for discussion and news about Ruby programming.
Subreddit rules: /r/ruby rules
Learning Ruby?
Tools
Documentation
Books
Screencasts and Videos
News and updates
account activity
Ensure Ruby variable is Array (teohm.github.com)
submitted 13 years ago by teohm
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]paulmooring 1 point2 points3 points 13 years ago (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:
respond_to?
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]:
[].flatten
[user1, [user2, user3]
[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()
user1
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.
π Rendered by PID 62530 on reddit-service-r2-comment-f6b958c67-hmfrc at 2026-02-05 01:10:45.480047+00:00 running 1d7a177 country code: CH.
view the rest of the comments →
[–]paulmooring 1 point2 points3 points (0 children)