Strings to Integers

2019-03-04 09:55发布

Say you have the string "Hi". How do you get a value of 8, 9 ("H" is the 8th letter of the alphabet, and "i" is the 9th letter). Then say, add 1 to those integers and make it 9, 10 which can then be made back into the string "Ij"? Is it possible?

4条回答
Evening l夕情丶
2楼-- · 2019-03-04 10:34

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"
查看更多
霸刀☆藐视天下
3楼-- · 2019-03-04 10:38

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"
查看更多
来,给爷笑一个
4楼-- · 2019-03-04 10:38

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"
查看更多
萌系小妹纸
5楼-- · 2019-03-04 10:49

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

'Hi'.chars.map{|x| (x.ord+1).chr}.join
查看更多
登录 后发表回答