Strings to Integers

拥有回忆 提交于 2019-12-02 10:39:36

use ord to get the ASCII index, and chr to bring it back.

'Hi'.chars.map{|x| (x.ord+1).chr}.join

Note Cary Swoveland had already given a same answer in a comment to the question.

It is impossible to do that through the numbers 8 and 9 because these numbers do not contain information about the case of the letters. But if you do not insist on converting the string via the number 8 and 9, but instead more meaningful numbers like ASCII code, then you can do it like this:

"Hi".chars.map(&:next).join
# => "Ij"

You can also create an enumerable of character ordinals from a string using the codepoints method.

string = "Hi"

string.codepoints.map{|i| (i + 1).chr}.join
=> "Ij"

Preserving case and assuming you want to wrap around at "Z":

upper = [*?A..?Z]
lower = [*?a..?z]
LOOKUP = (upper.zip(upper.rotate) + lower.zip(lower.rotate)).to_h
s.each_char.map { |c| LOOKUP[c] }.join
#=> "Ij"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!