How to increase or decrease a character in Ruby for all possible values?

I have a single character string and can be any possible character value:

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

I thought this might work:

 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 see, this is not so. How can I increase / decrease my character?


Edit:

Ruby does not seem to be configured for this. Maybe I'm getting it wrong. I want to manipulate raw data in terms of 8-bit chunks. How can I best perform such an operation?

+4
source share
4 answers

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

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

Or, to update an existing value:

 c = "\x0" c.next! 

This may not be the way you want:

 "z".next # => "aa" 

The easiest way I can multiply the growth of the character underlying the code is this:

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

Reducing a little harder:

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

In both cases there is an assumption that you will not go beyond 0..255 ; You may need to add checks to do this.

+15
source

You can not:

 "\x0" += 1 

Because in Ruby, this is short for:

 "\x0" = "\x0" + 1 

and this is a syntax error for assigning a value to a string literal.

However, given the integer n , you can convert it to a character using pack . For instance,

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

Similarly, you can convert a character to an integer using ord . For instance:

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

Using these methods, you can easily write your own zoom 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 back. You can use Array # pack to convert these bytes to a string. (Refer to the documentation for encoding parameters.)

+2
source

You can use the String#next method.

0
source

I think the most elegant method (for alphanumeric characters):

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

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

I re-read the question and see that my answer has nothing to do with the question. I have no answer to the manipulation of 8-bit values ​​directly.

0
source

Source: https://habr.com/ru/post/1494857/


All Articles