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

后端 未结 4 1974
北荒
北荒 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条回答
  • 2021-01-05 01:15

    You could use the String#next method.

    0 讨论(0)
  • 2021-01-05 01:16

    Depending on what the possible values are, you can use String#next:

    "\x0".next
    # => "\u0001"
    

    Or, to update an existing value:

    c = "\x0"
    c.next!
    

    This may well not be what you want:

    "z".next
    # => "aa"
    

    The simplest way I can think of to increment a character's underlying codepoint is this:

    c = 'z'
    c = c.ord.next.chr
    # => "{"
    

    Decrementing is slightly more complicated:

    c = (c.ord - 1).chr
    # => "z"
    

    In both cases there's the assumption that you won't step outside of 0..255; you may need to add checks for that.

    0 讨论(0)
  • 2021-01-05 01:25

    I think the most elegant method (for alphanumeric chars) would be:

    "a".tr('0-9a-z','1-9a-z0')
    

    which would loop the a through to z and through the numbers and back to a.

    I reread the question and see, that my answer has nothing to do with the question. I have no answer for manipulationg 8-bit values directly.

    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题