Ruby: undefined method 'to_set' for array?

Ruby: undefined method 'to_set' for array?

Problem Description:

I have a large array of chars:

input = ["p", "f", "p", "t" ... "g"]

I am attempting to take a slice of the array and convert it into a set:

sub = input.slice(0, 4).to_set

But the interpreter bombs:

undefined method `to_set' for ["p", "f", "p", "t"]:Array (NoMethodError)

Why is this happening? In irb this code executes with no issues.

Solution – 1

The Enumerable#to_set method is implemented by Ruby’s Set. It is not require-d by default hence why you get the error if you try to use it.

But in irb Set is already required. You can verify that by:

require 'set' # => false

This is something that has been raised up as an issue in irb before.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject