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

后端 未结 4 2007
北荒
北荒 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: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.

提交回复
热议问题