【问题标题】:Ruby: Discarding Variables from Multiple Assignment from ArrayRuby:从数组中的多个赋值中丢弃变量
【发布时间】:2015-04-27 18:29:25
【问题描述】:

对于从数组中给定的变量赋值:

a,b,c,d,e = [ "foo","bar","discard","discard","blah" ]

有没有办法只分配abe 并丢弃cd?在 perl (Perl assignment with a dummy placeholder) 中是否有 undef

【问题讨论】:

    标签: ruby


    【解决方案1】:

    是的。

    a,b,_,_,e = [ "foo","bar","discard","discard","blah" ]
    

    【讨论】:

    • 据我了解,_只是一个标准变量?它与使用任意变量有什么区别吗? a,b,undefined,undefined,e ?
    • @PressingOnAlways _ 只是另一个变量名。它通常用于表示未使用的变量(例如,当您需要提供一个带有您不需要的参数的块时)。
    • _ 不会导致未使用变量的警告(在启用警告的情况下运行时;ruby -w
    • 有时在数组中捕获一些值很方便。例如,a,b,*c,e = ["foo", "bar", "discard", "discard", "blah" ]c #=> ["discard", "discard"]
    • @PressingOnAlways:Ruby 的 _ variable (and any others with a leading underscore as of Ruby 2.0) is treated specially 专门用于此类一次性使用。
    【解决方案2】:

    您可以使用 splat 运算符。

     a,b,*,e = ["foo","bar",nil,nil,"blah"]
    

    【讨论】:

    • 我没见过这种用法。很有趣。
    【解决方案3】:

    如果数组较长,这是一个替代方案:

    a,b,e = [ "foo","bar","discard","discard","blah" ].values_at(0,1,4)
    

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 2017-02-19
      • 2018-11-10
      • 2014-11-27
      • 1970-01-01
      相关资源
      最近更新 更多