我的目标是将数组中单词中的字母转换为其相应的数字值,以便:
["I", "like", "elephants"]
变成
[[18], [21, 18, 20, 14], [14, 21, 14, 25, 17, 10, 23, 29, 28]]
我如何实现目标?
这是我当前的代码:
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
我不能将单词作为子数组分开;我得到:
[18, 21, 18, 20, 14, 14, 21, 14, 25, 17, 10, 23, 29, 28]
答案 0 :(得分:2)
您需要引入中间数组,您可以在其中将运算结果存储在单个单词上:
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
答案 1 :(得分:2)
基本上,您想要的是一个转换(映射)。首先,我将每个单词拆分为一个字符数组。然后,每个字符数组的每个字母变为整数。
words = ["I", "like", "elephants"]
words.map(&:chars).map { |letters| letters.map { |letter| letter.to_i 36 } }