From: Robert Klemme Date: 2005-01-08T22:21:25+09:00 Subject: Re: Construct [*nil] works differently in 1.6 and 1.8 "Gennady Bystritksy" schrieb im Newsbeitrag news:41DF1E8F.7020404@tonesoft.com... > Hi, rubyists > > In ruby 1.6 I use the following quite often to quickly convert to arrays: > > a = [ *o ] > > If 'o' is already an array, 'a' will be the same. No, there will be two arrays containing the same references. Note the difference: >> foo=%w{a b c d} => ["a", "b", "c", "d"] >> foo.id => 135018196 >> foo.to_a.id => 135018196 >> [*foo].id => 135018196 foo#to_a just returns self while [*foo] creates a new array. > If 'o' is non-nil, 'a' becomes an array with 'o' as a single element. > Otherwise, if 'o' is nil, 'a' becomes an empty array. Nice and clean. > > However, in 1.8 if 'o' is nil, 'a' becomes an array with a single element > nil. Which is more consistent IMHO. > In other words: > in 1.6 [ *nil ] -> [] > in 1.8 [ *nil ] -> [ nil ] > > Was this incompatibility introduced deliberately or is it a bug that > slipped through? I'd say the 1.6 code is inconsistent and that was fixed in later versions. > It becomes a problem (or rather inconvenience) in 1.8, as I cannot replace > [ *o ] with o.to_a as in 1.6, because ruby 1.8 gives warning "default > `to_a' will be obsolete" for instances of user defined classes. You can easily fix this by class Object; def to_a; [self] end end >> Object.new.to_a => [#] Note also that there is #to_ary which should be implemented if a class has a reasonable array representation: >> ObjectSpace.each_object(Module){|cl| p cl if cl.instance_methods.include? >> "to_ary" } Array => 365 Kind regards robert