Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

I have a string that is one character long 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 can see, it didn't. How can I increment/decrement my character?


Edit:

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?

like image 782
Michael Dorst Avatar asked Aug 01 '13 23:08

Michael Dorst


1 Answers

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.

like image 117
Darshan Rivka Whittle Avatar answered Sep 30 '22 18:09

Darshan Rivka Whittle