Function accepting argument list or array

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

On Wed, Apr 21, 2010 at 5:45 PM, Thomas A. [email protected]
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.

On Apr 21, 11:52 am, Jesús Gabriel y Galán [email protected]
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

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