我试图了解contents_support?在这个 Array 类的方法中使用注入。操作员的目的是什么&/它是如何工作的?我认为它是按位和运算符。&我找到了运营商的这个解释:
二元 & 运算符的最简单用法可能是在 Array 类中。
&是集合交集运算符,这意味着结果是两个数组中公共元素的集合。irb(main):001:0> [1,2,3] & [1,2,5,6] => [1, 2]
但是在这种情况下这意味着什么, wheretrue作为参数传递给injectwhere 某些对象(即局部变量items)可能不会响应发送的消息。你能解释一下什么contents_support?返回以及为什么&是必要的吗?上面提到的代码片段是否解释&了在下面的代码中思考的正确方法&?
class Array
def contents_support?(message)
self.inject(true) { |all_ok, item| all_ok = all_ok & item.respond_to?(message) }
end
def thunk(message, *args)
if contents_support?(message)
self.each { |item| args.empty? ? item.send(message) : item.send(message, args) }
else
raise "Not all contents of #{self.inspect} respond to method #{message}"
end
end
end