-->

为什么这里的数组定义中使用的图示?(Why is the splat used inside an

2019-07-17 20:48发布

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

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

在此方法机架级联::什么用处呢的splat(*)的发球局中[*catch]代码?

我想在方法的参数使用了图示,表示你什么时候有参数的数目不详。

请问图示具有不同的含义吗?

Answer 1:

它创建用于捕获单个扁平阵列

我不知道任何人都完全理解了图示操作。 很多时候,它会删除“arrayness”的一个水平上,但它不会删除最后一个级别。

这是可能得到它在这一情况下,至少。 不管它是否产生阵列,用于捕捉参数的一个单级catch是单一的数或数字的阵列。

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


Answer 2:

我想了解这一点的最好方法是看什么在发生irb

因此,让我们初始化一个空的哈希, @catch

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

现在,让我们看看会发生什么,当参数catch进到它的默认值404

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

这给了我们是怎么回事的一个更好的主意。 我们可以看到, splat操作被用来建立一个Hash的响应。 响应号码被用作一个key和真正被设置为value 。 所以不管有多少项在抓,我们仍然可以建立一个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}

我希望这有帮助。 这里是一个链接,帮我出一点点:

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



Answer 3:

另一种方式来看待它:左值图示是贪婪的,并包含许多相应的r值越好。



文章来源: Why is the splat used inside an array definition here?
标签: ruby splat