🕷 zenspider.com

by ryan davis



sitemap
Looking for the Ruby Quickref?

Splat is good for you

Published 2005-12-02 @ 14:17

Tagged ruby, thoughts

A recent post on projectionist shows two code examples:

1
2
3
4
5
6
7
8
9
10
11
  def foo(*args)
    [args].flatten.map do |arg|
      # ...
    end
  end

  def foo(*args)
    Array(args).map do |arg|
      # ...
    end
  end

and argues their (ugly) necessity. I think both examples fail to hit the mark (or there is a typo?) as they’ve ensured the initial codition simply by using *args. Allowing them to state the problem in a straightforward fashion:

1
2
3
4
5
6
7
8
9
10
11
  def foo(*args)
    args.flatten.map do |arg| # if you are trying to combine a bunch of arrays
      # ...
    end
  end

  def foo(*args)
    args.map do |arg|
      # ...
    end
  end

which, is much more natural. If I had to guess, I’d say they meant to not put the splat in front of args. I find using splat to be a better fit.