Browsing the ruleby source code, I noticed that they were calling Container(:and), which is something I rarely see. In fact, the only other place I’ve seen it is in the fabrication gem
A quick look showed that Container subclasses Array, and a quick hop into Pry showed that Array(:anything) #=> [:anything].
Another quick look at the ruby documentation for Array doesn’t shed much light on to this question.
What method is being called by Array(), where is it documented, how can one define a method like this, and is it considered “bad form” in ruby?
For your first question, the answer is that it makes an array of its parameters.
For your second, I have no clue, but it’s simple enough.
For your third, here it is: In Ruby, defining a global method with the same name as the class is considered good form only when used to construct or convert from object of that type of a more fundamental type. You should not define this method unless you are creating some sort of low type. You could define this for some class like
BigInt128but you shouldn’t forObscureOrSpecializedType678. There is also a design for these methods.If the data that you are passed is of the returned type, return it. If the data is of a directly related type, perform obvious conversions (
FixnumtoBigInt128). If the data passed in can be converted and is somewhat related (StringtoFixnum) convert it (this conversion is usually only forString). If the data can not be converted, throw an exception. You should NEVER return a “magic value”.The other use of this method is to create a semi-literal syntax for non-literal types. The best examples of this are
Rational()andComplex(). These functions, in addition to doing conversions, allow you to create rations and complex numbers in a more natural way (Rational(1, 2)vs.Rational.new(1, 2)). If there is a certain argument list that is simpler to the literal representation of a type, you would define aClassname()method.For the most part, these methods are only part of the core language, and unless you are making a class like
BigInt128orFancyStringorNaturalNumber, you should not define these methods.From what I know the defined of these are:
Array(*args)— Returns arguments as an arrayComplex(real, complex)— Create a complex number with given real and complex partsFloat(arg)— Returnsargconverted to a float (takes things like strings too)Integer(arg)— Same asFloat(), but converts to an integer(floats are truncated)Rational(numerator, denominator=1)— Creates a Rational number with the given partsString(arg)— Converts argument to string by callingto_sAlso, some classes define
[]as a class method, which is used for more complex initialization from basic data types (usual initialization only, not conversion) such asHash[].