【问题标题】:What does :^ in reduce method mean?减少方法中的 :^ 是什么意思?
【发布时间】:2019-10-23 20:16:17
【问题描述】:

我在 Code Wars 上进行了一项挑战,我得到了一个包含多个(有时是重复的)整数的数组“数字”,我必须返回一个唯一的整数。我通过了挑战,但是当我查看之前提交的所有解决方案时,我注意到了这个 reduce 方法:

def stray (numbers)
  numbers.reduce(&:^)
end

我知道 reduce 方法通常是做什么的,但我无法找到符号 ^ 的含义。谁能告诉我它的用途?

【问题讨论】:

  • 提示:Integer#^ 是按位异或。而Enumerable#reduce 通过应用该操作来组合数组的所有元素。
  • 非提示:...而numbers.reduce(&:^)numbers.reduce { |result, result ^ n } 的简写。顺便说一句,在这种情况下,可以简化为:numbers.reduce(:^)。后者使用Enumerable#reduce(又名inject)的第二种形式。
  • 你知道foo(&:bar)是什么意思吗?你知道:bar 在那个sn-p 中是什么意思吗?那么,从逻辑上讲,:^ 在 sn-p reduce(&:^) 中是什么意思?

标签: ruby reduce


【解决方案1】:

reduce 方法用于数组,以将该数组的所有元素组合成一个项目。

reduce 方法接受一个起始值和一个代码块。

您使用的是 reduce 的简写版本,含义如下:

numbers.reduce(&:^)

当 & 字符用作方法调用或定义的最后一个参数时,它会尝试调用参数本身的方法。 ^ 字符表示按位XOR operator

Inject 也是 Ruby 中 reduce 的别名。

您可以阅读更多here

【讨论】:

    猜你喜欢
    • 2011-11-13
    • 2016-10-17
    • 2013-11-02
    • 1970-01-01
    • 2013-03-29
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    相关资源
    最近更新 更多