Why is the splat used inside an array definition here?

前端 未结 3 1131
天涯浪人
天涯浪人 2021-01-05 20:26
def initialize(apps, catch=404)
  @apps = []; @has_app = {}
  apps.each { |app| add app }

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


        
3条回答
  •  灰色年华
    2021-01-05 21:12

    I think the best way to understand this is to look what is happening in irb.

    So let's initialize an empty hash, @catch:

    >> @catch = {}
    => {}
    >> @catch.class
    => Hash
    

    Now let's see what happens when the parameter catch goes to it's default value of 404:

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

    This gives us a better idea of what is going on. We can see that the splat operator is being used to build a Hash of responses. The response numbers are being used as a key and true is set as the value. So no matter how many items we have in catch, we can still build a Hash.

    >> catch=[404, 301, 302, 303, 403]
    => [404, 301, 302, 303, 403]
    >> [*catch].each { |status| @catch[status] = true }
    => [404, 301, 302, 303, 403]
    >> @catch
    => {302=>true, 303=>true, 403=>true, 404=>true, 301=>true}
    

    I hope this helps. Here is a link that helped me out a little bit:

    http://theplana.wordpress.com/2007/03/03/ruby-idioms-the-splat-operator/

提交回复
热议问题