NoMethodError: Intersection function method not found for arrays

Viewed 257

I am writing a script where I would like to use the .intersection method on Array. But when I call the method on an array I get NoMethodError. See full IRB output:

larsnielsen@darkstar ruby % irb
irb(main):001:0> x = ["a", "b"]
=> ["a", "b"]
irb(main):002:0> y = ["a", "c"]
=> ["a", "c"]
irb(main):003:0> x.intersection y
Traceback (most recent call last):
        4: from /Users/larsnielsen/.rbenv/versions/2.6.5/bin/irb:23:in `<main>'
        3: from /Users/larsnielsen/.rbenv/versions/2.6.5/bin/irb:23:in `load'
        2: from /Users/larsnielsen/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        1: from (irb):3
NoMethodError (undefined method `intersection' for ["a", "b"]:Array)

I am running Ruby 2.6.5p114 and from what I can tell the function should exist in this version.

Minimal working example:

x = ["a", "b"]
y = ["a", "c"]
x.intersection y
2 Answers
x = ["a", "b"]
y = ["a", "c"]
x & y #["a"]

You can follow above code to accomplish your Array intersection.

Firstly, you should check version Ruby in your computer intersection method only support for Ruby 2.6

If you using ruby 2.5, you could &

Related