Search code examples
rubyenumsnomethoderrorpartition

NoMethodError: Undefined Method When Using Partition Enumerable


I read about the Ruby Enumerable partition and wanted to refactor my credit card validator project include it.

class CreditCheck

  attr_reader :number, :flipped, :split

  def initialize(number)
@number = number.split("").map { |s| s.to_i}
end

  def flip_number
@flipped = @number.reverse
  end

  def check_validity
@split = @flipped.partition.with_index { |x , index|
  index.even?}
@split
  end

end

This returns:

NoMethodError: undefined method `partition' for nil:NilClass

Any help on how to fix this? I'm sure I am just missing a small detail.


Solution

  • In check_validity method replace @flipped for the method flip_number

     @split = flip_number.partition.with_index { |x , index| index.even?}