0

I have asked a similar question earlier: reference to a method?

but now I am trying to figure out how to do this with this code:

arr0 = [1,2,3]
arr1 = [2,3,4,5]
arr1.reject! {|x|
    arr0.include? x
}

apparently {|x| arr0.include? x} can be simplified to just arr0.include?. But I do not know how to get this method reference.

EDIT: I am not interested in how to subtract arrays in Ruby using a simpler syntax. I am looking for a way to get a reference to a method.

Community
  • 1
  • 1
akonsu
  • 28,824
  • 33
  • 119
  • 194

4 Answers4

6
arr1.reject!(&arr0.method(:include?))
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • @steenslag: The ampersand in a *parameter list* means "wrap this block in a `Proc`". The ampersand in an *argument list* means "unwrap this `Proc` into a block (and call `to_proc` on it first, if it isn't already a block)". `Method` implements `to_proc`, just like `Symbol` does, so, it works exactly the same way as it does with `Symbol`s. – Jörg W Mittag Sep 30 '12 at 22:23
1

You can do that with

arr1 - arr0

and you can't do that with a pretzel colon, because you have an argument.

1

Each Object in Ruby has a method 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
steenslag
  • 79,051
  • 16
  • 138
  • 171
1
arr0 = [1,2,3]
arr1 = [2,3,4,5]

m = arr0.method(:include?)
arr1.reject!(&m) #=> [4, 5]
megas
  • 21,401
  • 12
  • 79
  • 130