Search code examples
rubysplat

Why is the splat used inside an array definition here?


def initialize(apps, catch=404)
  @apps = []; @has_app = {}
  apps.each { |app| add app }

  @catch = {}
  [*catch].each { |status| @catch[status] = true }
end

In this method from Rack::Cascade, what purpose does the splat(*) serve in the [*catch] code?

I thought a splat was used in method arguments to indicate when you are going to have an unspecified number of parameters.

Does the splat have a different meaning here?


Solution

  • It creates a single flat array for catch

    I'm not sure anyone completely understands the splat operator. Many times it removes one level of "arrayness", but it won't remove the last level.

    It is possible to get it in this one case, at least. It creates a single level of array for the catch parameter regardless of whether catch is a single number or an array of numbers.

    >> t = [*404]
    => [404]
    >> t = [*[404,405,406]]
    => [404, 405, 406]