This series is invaluable. I have been programming in Ruby professionally for over 7 years and did not know about Array()! Since then I have been joyfully combing through my repos and eliminating literally dozens of
obj = [obj] unless obj.type_of?(Array)
Integer() was another head-slapper that I can't believe I didn't know. And the series is full of them.
Be careful with Array() since it uses #to_a method whenever it exists. As such, this trick is unsuitable for array of hashes (in any version of ruby) and strings (in ruby 1.8).
Other Enumerables might make for unpleasant surprise too.
Old mootools had $A method (called Array.from now) which did exactly what you expected.
And I agree...I've been programming in Ruby for awhile and only lately had learned about the `Array()` conversion, which I learned through Avdi Grimm's "Confident Ruby" book (he blogged about Array several years ago: http://devblog.avdi.org/2009/10/21/array-ifying-values/).
Such a small thing, but as you note, can greatly impact the cruft in your error-checking interfaces.
Most if not all of this is in the language documentation. It's the best source, along with the actual implementation for learning this stuff. A good way to learn is to try to read docs for one module a day.
Ah you're right. Hadn't actually tested this. The way that I've actually used it is for `is_num?` and using `Float()`. I didn't consider the fact that `Integer` would cast a float.
Doing open source, you learn little nuggets like this. I learned about `Array()` when checking out how Rails routing allowed you to pass a symbol or an array, like:
A lot of that stuff comes with the dynamite combination of pry and its various plugins: pry-debugger (gives you next, step etc), pry-stack_explorer (go up and down the call stack) and so on.
I implore you to check them out if you are a ruby developer. I can't remember how I got work done without them.
require 'pry'
class Stuff
def initialize
binding.pry
end
end
Stuff.new # diy console
Also, awesome_print is a lifesaver as well...
One tip I do have is: be careful when "prying" you don't want to accidentally ship a "binding.pry" into production (*I did it to our staging server once-- both hilarious and stupid)
Thanks very much to the Author(s)!