[Solved] Ruby code doesn’t work [closed]


I checked your codes and found some problems:

 num_array.reverse.each_with_index { |value , index|
    if index % 3 == 0 && num_array[index] != 0 
      num_string = num_string << ones_place[value-1]
    elsif index % 3 == 0 && value > 0 && num_array[index] != 0
      num_string = num_string << other_place[index/3] << ones_place[value-1]
    elsif index % 3 == 1
      num_string = num_string << tens_place[value-1]
    elsif index & 3 == 2
      num_string = num_string << other_place[0] << ones_place[value-1]
    end
  }

ones_place[value-1] is possibly nil, you try to add nil to string, so TypeError raised. if ones_place[value-1] is nil, you should change it into string, just need to use to_s method or use + to add strings together.

"" << nil
TypeError: no implicit conversion of nil into String

"" << nil.to_s
=> ""

I modify the code as below, the script can works, no errors found, but I don’t know the result is right or not, you should check it by yourself.

  num_array.reverse.each_with_index { |value , index|
    puts "#{value} and #{index}"
    if index % 3 == 0 && num_array[index] != 0
      num_string = num_string + ones_place[index-1]
    elsif index % 3 == 0 && value > 0 && num_array[index] != 0
      num_string = num_string + other_place[index/3] + ones_place[index-1]
    elsif index % 3 == 1
      num_string = num_string + tens_place[index-1]
    elsif index & 3 == 2
      num_string = num_string + other_place[0] + ones_place[index-1]
    end
  }

I suggest you add some debug code to your script, it can help you find problems as soon as possible.

solved Ruby code doesn’t work [closed]