ruby - 压缩 {|n1, n2| Ruby 中的 n1 ^ n2}

标签 ruby symbols proc

我不太喜欢 Ruby,所以我可能会错过一些非常基本的东西,但我还想不出来:假设我有一个包含任意数量的 2 元素整数数组的数组。我想按位异或每组两个整数。
我目前使用的是非常明显的

l.map {|n1, n2| n1 ^ n2}

不过,我的第一个想法是按照 l.map &:^ 的思路做一些事情。显然这是不可能的,因为不存在 Array#^ 这样的东西,并且生成的 proc 不会进行参数解包。有没有一种很好的方法可以使用符号来处理逻辑,或者我是否坚持使用功能性但我目前使用的无疑不太优雅的解决方案?

问候,
磷酸铜

最佳答案

有一种方法可以使用 Symbol#to_proc 来做到这一点,但它不会比您已有的(很好的)解决方案更好,因为它涉及定义 Array# ^.

class Array
  def ^
    raise("Not a two-element array") unless (self.length == 2)
    raise("Array contains non-numeric values") unless (self.all? {|n| Integer === n })

    return self[0] ^ self[1]
  end
end

l.map(&:^)

关于ruby - 压缩 {|n1, n2| Ruby 中的 n1 ^ n2},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700255/

相关文章:

android - 在 Android 中将符号转换为 HTML 实体代码

visual-studio-2010 - VS2010 : "No matching binary found" when trying to load symbols for crashdump

Python 产量(从 Ruby 迁移): How can I write a function without arguments and only with yield to do prints?

ruby-on-rails - Ruby on Rails 中的 Gem 路径错误

ruby-on-rails - 如果 NOT nil 获取 ActiveRecords

java - 返回 printf(),找不到符号

ruby - 为什么将方法作为参数 (&block) 传递不起作用?

ruby - 你将如何在 ruby​​ 2.0 中实现与信号的保存线程协作?

javascript - 在 Google Chrome 上待处理的 Ruby on Rails 请求

ruby - 如何在 `&` -`&` 往返下保存 proc 对象?