Home > database >  Ruby: undefined method 'to_set' for array?
Ruby: undefined method 'to_set' for array?

Time:12-06

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.

CodePudding user response:

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.

CodePudding user response:

In the Ruby programming language, there is no to_set method available for the Array class. The to_set method is available for the Set class, which is a different data structure than an array. In order to convert an array to a set, you can use the Set class's new method and pass in the array as an argument. Example:

input = ["p", "f", "p", "t", "g"]
sub = Set.new(input.slice(0, 4))

This code will create a new set containing the elements from the input array that are indexed at 0, 1, 2, and 3 (the first four elements of the array).

  •  Tags:  
  • ruby
  • Related