From: Shadowfirebird Date: 2008-08-13T04:58:08+09:00 Subject: Re: How do I unsplat something? # How about: def unsplat(thing) if thing.kind_of?(Array) thing else [thing] end end On Tue, Aug 12, 2008 at 8:47 PM, Chris Shea wrote: > On Aug 12, 1:14 pm, Patrick Li wrote: >> I can't use Array() because I want: >> {"a"=>2} to become [{"a"=>2}] >> >> so far: flatten is the best so far... except that it recursively >> flattens inner arrays too... which is not ideal but workable for my >> current use. >> >> -- >> Posted viahttp://www.ruby-forum.com/. > > There was a ruby quiz that included implementations of a single-level > flatten[1]. Taking from James Gray's solution[2], and minding your > requirements regarding hashes, what about this: > > def unsplat(the_splatted) > if the_splatted.kind_of?(Hash) > [the_splatted] > else > [the_splatted].inject(Array.new) { |arr, a| arr.push(*a) } > end > end > > unsplat(1) # => [1] > unsplat([2,3]) # => [2, 3] > unsplat([4,[5,6]]) # => [4, [5, 6]] > unsplat({'a'=>2}) # => [{"a"=>2}] > > HTH, > Chris > > [1] http://www.rubyquiz.com/quiz113.html > [2] http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/238693 > > -- All you can do is try to know who your friends are as you head off to the war / Pick a star on the dark horizon and follow the light