Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the effect in Ruby when you initialize with nil: x = String(nil)

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?

like image 874
nickl Avatar asked Jul 10 '26 12:07

nickl


1 Answers

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.

like image 120
Phil Ross Avatar answered Jul 13 '26 14:07

Phil Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!