动态地解析Ruby块参数

eas*_*fri 2 ruby arrays block

最近关于ruby解构的好文章将解构定义为将一组变量绑定到相应的一组值的能力,这些值通常可以将值绑定到单个变量,并给出了块解构的示例

triples = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

triples.each { |(first, second, third)| puts second } =>#[2, 5, 8]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我们知道主数组中元素的数量,因此当我们提供参数first,second,third时,我们可以得到相应的结果.那么如果我们有一个数组的数组,其大小是在运行时确定的呢?

triples = [[1, 2, 3], [4, 5, 6], [7, 8, 9],...,[]]
Run Code Online (Sandbox Code Playgroud)

我们想要获得每个子阵列的第一个条目的元素?

triples.each { |(first, second, third,...,n)| puts first }
Run Code Online (Sandbox Code Playgroud)

(first, second, third,...,n)动态创建局部变量的最佳方法是什么?

mu *_*ort 6

在您的特定情况下,您将使用splat收集除第一个值之外的所有内容:

triples.each { |first, *rest| puts first }
#-----------------------^splat
Run Code Online (Sandbox Code Playgroud)

*rest符号只是收集剩下的成称为数组的一切rest.

一般来说,创建任意数量的局部变量(second, third, ..., nth)没有多大意义,因为你无法对它们做任何事情; 你可能会惹恼一堆恶意但我们已经拥有一个优秀且功能齐全的数组类,所以为什么要费心呢?