From: Rob Biedenharn Date: 2007-07-26T04:38:47+09:00 Subject: Re: opposite of [thing].flatten On Jul 25, 2007, at 3:10 PM, Phlip wrote: > Ruby-ists: > > We all know this clever idiom to turn a variable that might be an > Array into > one known to be an Array: > > thing = [thing].flatten > > That saves a lot of if statements to permit thing's type to overload. > > What is the opposite (clever) operation? How to turn a list of one > item into > one item, and a list of zero items into nil, but pass thru the list > of many > items? > > -- > Phlip > http://www.oreilly.com/catalog/9780596510657/ > ^ assert_xpath > http://tinyurl.com/23tlu5 <-- assert_raise_message Except for the fact that it is deprecated, use .to_a: irb(main):001:0> nil.to_a => [] irb(main):002:0> "one".to_a => ["one"] irb(main):003:0> [1,2,3].to_a => [1, 2, 3] ------------------------------------------------------------ Object#to_a obj.to_a -> anArray ------------------------------------------------------------------------ Returns an array representation of _obj_. For objects of class +Object+ and others that don't explicitly override the method, the return value is an array containing +self+. However, this latter behavior will soon be obsolete. self.to_a #=> -:1: warning: default `to_a' will be obsolete "hello".to_a #=> ["hello"] Time.new.to_a #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, "CDT"] -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com