views:

67

answers:

1

What's the effect in Ruby when you pass nil to the constructor as in:

s = String(nil)

or

a = Array(nil)

Does this mean that s or a is nil or that s or a is an unpopulated object of type String or type Array?

+7  A: 

String(arg) calls to_s on arg and returns the result. nil.to_s returns a new empty string. String(nil) therefore returns a new empty string.

Array(arg) attempts to call to_ary and then to_a on arg, returning the result of the first method that exists (or [arg] if neither method exists). NilClass doesn't have a to_ary method, but nil.to_a returns a new empty array. Array(nil) therefore returns a new empty array.

Note that String(arg) and Array(arg) aren't constructors. They are just global methods defined in Kernel. To construct objects in Ruby, you typically call new on a class, e.g. Array.new(2) to create an array of length 2.

Phil Ross