Strings to Integers

前端 未结 4 337
温柔的废话
温柔的废话 2021-01-26 09:57

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\"

相关标签:
4条回答
  • 2021-01-26 10:17

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

    'Hi'.chars.map{|x| (x.ord+1).chr}.join
    
    0 讨论(0)
  • 2021-01-26 10:23

    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"
    
    0 讨论(0)
  • 2021-01-26 10:26

    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"
    
    0 讨论(0)
  • 2021-01-26 10:32

    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"
    
    0 讨论(0)
提交回复
热议问题