How do I increment/decrement a character in Ruby for all possible values?

后端 未结 4 1996
北荒
北荒 2021-01-05 00:48

I have a string that is one character long and can be any possible character value:

irb(main):001:0> \"\\x0\"
=> \"\\u0000\"

I though

4条回答
  •  梦毁少年i
    2021-01-05 01:40

    You cannot do:

    "\x0" += 1
    

    Because, in Ruby, that is short for:

    "\x0" = "\x0" + 1
    

    and it is a syntax error to assign a value to a string literal.

    However, given an integer n, you can convert it to a character by using pack. For example,

    [97].pack 'U' # => "a"
    

    Similarly, you can convert a character into an integer by using ord. For example:

    [300].pack('U').ord # => 300
    

    With these methods, you can easily write your own increment function, as follows:

    def step(c, delta=1)
      [c.ord + delta].pack 'U'
    end
    
    def increment(c)
      step c, 1
    end
    
    def decrement(c)
      step c, -1
    end
    

    If you just want to manipulate bytes, you can use String#bytes, which will give you an array of integers to play with. You can use Array#pack to convert those bytes back to a String. (Refer to documentation for encoding options.)

提交回复
热议问题