1

When I run this code I get a typeError, but when I do it by hand in the IRB everything seems to be working out okay. I believe the problem lies somewhere in my IF statement but I don't know how to fix it.

numerals = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
def convertToNumbers(string)
  arr = string.downcase.split('')
  new_array = []
  arr.each do |i|
      if (arr[i] =~ [a-z])
          numValue = numerals.index(arr[i]).to_s
          new_array.push(numValue)
      end
  end
end
2
  • You should be a using a text editor with good code highlighting. It would have helped you notice your typo. Commented Jan 10, 2019 at 22:39
  • You appear to be doing arr.each |i|, but then doing arr[i] instead of just i. Commented Jan 10, 2019 at 23:10

2 Answers 2

3

You probably meant

arr[i] =~ /[a-z]/

which matches the characters a through z. What you wrote

arr[i] =~ [a-z]

is constructing an array and trying to compare it using the regex comparison operator, which is a type error (assuming variables a and z are defined).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the response but I'm still getting the same error when i run the program
2

A few issues. As Tyler pointed out inside of the loop you are still referencing arr when you look to only need to use i. Also, the regex issue Max pointed out is valid as well. The function also will return arr and not the new_array array as that is the result of the for loop output.

I made a few modifications.

def convertToNumbers(string)
  numerals = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
  arr = string.downcase.split('')
  new_array = []
  arr.each do |i|
      if (i =~ /[a-z]/)
          numValue = numerals.index(i).to_s
          new_array.push(numValue)
      end
  end
  new_array.join
end

puts convertToNumbers('abcd');

which prints out '0123'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.