From: Paul Mckibbin Date: 2008-03-11T08:08:43+09:00 Subject: Re: shortcut for x = [x] unless x.is_a?(Array) Aryk Grosz wrote: > Is there any prettier or cleaner way to write > > x = [x] unless x.is_a?(Array) Lots of caveats, caution and make sure you really, really are thinking about what you are trying to do. But with that note of skepticism aside....... I'd guess what you really want is: x=Array(x) This will give you the same behaviour for String, Fixnum, TrueClass, Regexp and Array as your line, and is probably more what you want for Nil, Range and Hash. I'm second guessing, but this may not be the wisest way of writing your code. Are you trying to get around the fact that x=x.to_a default behavior will be obsoleted in v1.9? Make sure that is really what you want. The answer depends on what you are trying to convert from. I'd use something like this to make sure this is really what you want to achieve. TEST=[[1,2,3],(1..3),{:a=>:b},1,"test",true,nil,/123/] TEST.each do |x| puts x.class puts '============================' puts "#{x.inspect}.to_a => #{x.to_a.inspect}" puts "[#{x.inspect}] => #{([x]).inspect}" puts "Array(#{x.inspect}) => #{Array(x).inspect}" puts '============================' end OUTPUT ============================ [1, 2, 3].to_a => [1, 2, 3] [[1, 2, 3]] => [[1, 2, 3]] <----- this seems to be the only case that you are catering for Array([1, 2, 3]) => [1, 2, 3] ============================ Range ============================ 1..3.to_a => [1, 2, 3] [1..3] => [1..3] Array(1..3) => [1, 2, 3] ============================ Hash ============================ {:a=>:b}.to_a => [[:a, :b]] [{:a=>:b}] => [{:a=>:b}] Array({:a=>:b}) => [[:a, :b]] ============================ Fixnum ============================ 1.to_a => [1] [1] => [1] Array(1) => [1] ============================ String ============================ "test".to_a => ["test"] ["test"] => ["test"] Array("test") => ["test"] ============================ TrueClass ============================ true.to_a => [true] [true] => [true] Array(true) => [true] ============================ NilClass ============================ nil.to_a => [] [nil] => [nil] Array(nil) => [] ============================ Regexp ============================ /123/.to_a => [/123/] [/123/] => [/123/] Array(/123/) => [/123/] ============================ -- Posted via http://www.ruby-forum.com/.