Home > Blockchain >  no implicit conversion from nil to integer, couldn't figure out why
no implicit conversion from nil to integer, couldn't figure out why

Time:06-22

Trying to populate a 2D array with letters in Ruby don't understand why it is giving the error

alpha = ("A".."Z").to_a
letters_range = alpha[0...size*size/2]
chosen_letters = (letters_range   letters_range).shuffle 
(0...size).each do |row|
    (0...size).each do |col|
        letter = chosen_letters.select
        @grid[row][col] = Card.new(letter)
        letter_idx = chosen_letters.index(letter)
        chosen_letters.delete_at(letter_idx)  #error line
    end
end

CodePudding user response:

chosen_letters is an array containing single-character strings.

When running letter = chosen_letters.select, you may assume that Array#select returns a random element. However, when not passing it a block, it returns an Enumerator. As such, your letter variable does not contain an element from the chosen_letter array and thus, an index for this object can not be found, resulting in letter_idx to be nil.

To fix this, you may want to use a more appropriate statement to fetch an element, e.g. Array#pop to return and remove the last element from the array.

  • Related