From: Thomas Allen on 21 Apr 2010 11:43 How would I write a function that treats fn(:a, :b) the same as it does fn([:a, :b])? The only way I can do this right now is by checking if the first argument is an array, but I thought there was a simpler way to do this, involving the splat operator '*'. Thomas
From: Jesús Gabriel y Galán on 21 Apr 2010 11:52 On Wed, Apr 21, 2010 at 5:45 PM, Thomas Allen <thomasmallen(a)gmail.com> wrote: > How would I write a function that treats fn(:a, :b) the same as it > does fn([:a, :b])? The only way I can do this right now is by checking > if the first argument is an array, but I thought there was a simpler > way to do this, involving the splat operator '*'. irb(main):013:0> def method *args irb(main):014:1> p args irb(main):015:1> end => nil irb(main):016:0> method 1,2 [1, 2] => nil irb(main):017:0> method [1,2] [[1, 2]] => nil irb(main):018:0> method *[1,2] [1, 2] => nil If you can change the call to using the splat when you have an array, then this works. If not you can do this: irb(main):019:0> def method *args irb(main):020:1> args = args.flatten irb(main):021:1> p args irb(main):022:1> end => nil irb(main):023:0> method 1,2 [1, 2] => nil irb(main):024:0> method [1,2] [1, 2] although be careful, this will flatten nested arrays all along (don't know if this is good or bad for you): irb(main):025:0> method [[1,2],[3,4]] [1, 2, 3, 4] Jesus.
From: Thomas Allen on 21 Apr 2010 11:58 On Apr 21, 11:52 am, Jesús Gabriel y Galán <jgabrielyga...(a)gmail.com> wrote: > although be careful, this will flatten nested arrays all along (don't > know if this is good or bad for you): No, this works well for what I'm doing, thanks for the help. Thomas
From: Robert Klemme on 21 Apr 2010 12:17 On 04/21/2010 05:52 PM, Jesús Gabriel y Galán wrote: > although be careful, this will flatten nested arrays all along (don't > know if this is good or bad for you): > > irb(main):025:0> method [[1,2],[3,4]] > [1, 2, 3, 4] You can control that at least in 1.8.7 and 1.9.*: irb(main):001:0> a=[[[1,2],3],4] => [[[1, 2], 3], 4] irb(main):002:0> a.flatten => [1, 2, 3, 4] irb(main):003:0> a.flatten 1 => [[1, 2], 3, 4] irb(main):004:0> Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/
|
Pages: 1 Prev: Ruby 1.9.1, Threads and "The handle is invalid." Next: [ANN] clogger 0.4.0 - small cleanups |