【问题标题】:Explain this Ruby Array Syntax解释这个 Ruby 数组语法
【发布时间】:2012-03-24 18:49:15
【问题描述】:

Jekyll gem 的第一行bin/jekyll 使用以下语法:

$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])

我似乎无法弄清楚 splat 的目的是什么。在 IRB 中使用和不使用 splat 运行该行会产生相同的输出 "./../lib"

https://github.com/mojombo/jekyll/blob/master/bin/jekyll

【问题讨论】:

    标签: ruby rubygems jekyll


    【解决方案1】:

    至少在 Ruby 1.9.3 中,join 方法的两种用法似乎是等效的。 Under the hood,数组的元素被 join 递归到路径中,具有针对无限递归的特殊保护。

    因此,这很好用:

    File.join 'a', ['b', ['c']]
    

    有人可能会争辩说,splat 运算符的目的是消除递归。问题在于:

    File.join 'a', *['b', ['c']]
    

    相当于这个:

    File.join 'a', 'b', ['c']
    

    为了消除递归,你必须flatten 数组然后然后 splat:

    File.join 'a', *['b', ['c']].flatten
    

    在参数列表的上下文中,splat 运算符“删除”数组的括号,可以这么说。结果是这样的:

    # File.join receives 3 strings as parameters
    $:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
    

    与此相反:

    # File.join receives 2 parameters, one string and one array of strings
    $:.unshift File.join(File.dirname(__FILE__), ['..', 'lib'])
    

    More information about the splat operator.

    【讨论】:

      【解决方案2】:

      * 使参数变平。等效于没有 splat:

      File.join(File.dirname(__FILE__), ["..", "lib"])
      

      相当于splat:

      File.join(File.dirname(__FILE__), "..", "lib")
      

      我想在这种情况下File.join 会以同样的方式对待它。但是请注意,documentation 暗示它们应该被展平。现在,为什么作者不简单地写没有数组或 splats 是另一回事。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-19
        • 1970-01-01
        • 2016-01-15
        • 1970-01-01
        • 2013-11-19
        • 1970-01-01
        • 2013-06-09
        • 1970-01-01
        相关资源
        最近更新 更多