问题描述
我有一个长度为一个字符的字符串,可以是任何可能的字符值:
I have a string that is one character long and can be any possible character value:
irb(main):001:0> "\x0"
=> "\u0000"
我认为这可能有效:
irb(main):002:0> "\x0" += 1
SyntaxError: (irb):2: syntax error, unexpected tOP_ASGN, expecting $end
"\x0" += 1
^ from /opt/rh/ruby193/root/usr/bin/irb:12:in `<main>'
但是,正如你所看到的,它没有.如何增加/减少我的角色?
But, as you can see, it didn't. How can I increment/decrement my character?
Ruby 似乎没有设置为执行此操作.也许我以错误的方式接近这个.我想以 8 位块的形式操作原始数据.我怎样才能最好地完成这种操作?
Ruby doesn't seem to be set up to do this. Maybe I'm approaching this the wrong way. I want to manipulate raw data in terms of 8-bit chunks. How can I best accomplish that sort of operation?
推荐答案
根据可能的值是什么,您可以使用 String#next
:
Depending on what the possible values are, you can use String#next
:
"\x0".next
# => "\u0001"
或者,更新现有值:
c = "\x0"
c.next!
这可能不是您想要的:
"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
# => "{"
递减稍微复杂一些:
c = (c.ord - 1).chr
# => "z"
在这两种情况下,都假设您不会超出 0..255
;您可能需要为此添加检查.
In both cases there's the assumption that you won't step outside of 0..255
; you may need to add checks for that.
这篇关于如何在 Ruby 中为所有可能的值增加/减少一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!