0

My goal is to convert letters within words in an array into their corresponding number values so that:

["I", "like", "elephants"]

turns into

[[18], [21, 18, 20, 14], [14, 21, 14, 25, 17, 10, 23, 29, 28]]

How can I attain my goal?

This is my current code:

words = ["I", "like", "elephants"]
seperate_words = []
converted_words = []

words.each do |word|
  seperate_words.push(word.split(//))
end
puts seperate_words.to_s

seperate_words.each do |word|
  word.each do |letter|
    converted_words.push(letter.to_i 36)
  end
end
puts converted_words.to_s

I cannot separate the words as sub-arrays; I get:

[18, 21, 18, 20, 14, 14, 21, 14, 25, 17, 10, 23, 29, 28]

2 Answers 2

2

You need to introduce intermediate array, where you can store the results of operation on a single word:

separate_words.each do |word|
  converted_word = []
  word.each do |letter|
    converted_word.push(letter.to_i(36))
  end
  converted_words.push(converted_word)
end
Sign up to request clarification or add additional context in comments.

Comments

2

Basically what you want is a transformation (map). First, I split every word in an array of characters. then, every letter of every array of character becomes an integer.

words = ["I", "like", "elephants"]
words.map(&:chars).map { |letters| letters.map { |letter| letter.to_i 36 } }

6 Comments

Basically what you want is a transformation. First, I split every word in an array of characters. then, every letter of every array of character becomes an integer.
That's a good one, why don't you put this explanation in answer itself?
You could also do it as such words.map { |w| w.chars.map { |c| c.to_i(36) } }.
Is there any way for me to use this function to do the oppsite, i.e. to convert the numbers back into letters?
That is, once I've converted them from letters to numbers, how do I convert the numbers back to letters? @Ursus
|

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.