我之前曾问过类似的问题:reference to a method?
但现在我试图弄清楚如何使用此代码执行此操作:
arr0 = [1,2,3]
arr1 = [2,3,4,5]
arr1.reject! {|x|
arr0.include? x
}
显然{|x| arr0.include? x}
可以简化为arr0.include?
。但我不知道如何获得此方法参考。
编辑:我对如何使用更简单的语法减去Ruby中的数组感兴趣。我正在寻找一种获取方法参考的方法。
答案 0 :(得分:6)
arr1.reject!(&arr0.method(:include?))
答案 1 :(得分:1)
你可以用
做到这一点arr1 - arr0
并且您不能使用椒盐卷饼冒号,因为您有一个参数。
答案 2 :(得分:1)
Ruby中的每个对象都有一个method
方法:
m = [1,2,3].method(:include?) #reference to the include? method of this array.
p m.call(1) #call the method with an argument ; => true
答案 3 :(得分:1)
arr0 = [1,2,3]
arr1 = [2,3,4,5]
m = arr0.method(:include?)
arr1.reject!(&m) #=> [4, 5]