songyy
songyy

Reputation: 4563

Ruby String ASCII operation?

Is it possible to do some ASCII options in Ruby, like what we did in Cpp?

char *s = "test string";
for(int i = 0 ; i < strlen(s) ; i++) printf("%c",s[i]);
// expected output: vguv"uvtkpi

How do I achieve a similar goal in Ruby? From some research I think String.each_byte might help here, but I'm thinking to use high order programming (something like Array.map) to translate the string directly, without using an explicit for loop.

The task I'm trying to solve: Referring to this page, I'm trying to solve it using Ruby, and it seems a character-by-character translation is needed to apply to the string.

Upvotes: 1

Views: 191

Answers (3)

falsetru
falsetru

Reputation: 369014

Use String#each_char and String#ord and Integer#chr:

s = "test string"
s.each_char.map { |ch| (ch.ord + 2).chr }.join
# => "vguv\"uvtkpi"

or String#each_byte:

s.each_byte.map { |b| (b + 2).chr }.join
# => "vguv\"uvtkpi"

or String#next:

s.each_char.map { |ch| ch.next.next }.join
# => "vguv\"uvtkpi"

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160551

Pay close attention to the hint given by the question in the Challenge, then use String's tr method:

"test string".tr('a-z', 'c-zab')
# => "vguv uvtkpi"

An additional hint to solve the problem is, you should only be processing characters. Punctuation and spaces should be left alone.

Use the above tr on the string in the Python Challenge, and you'll see what I mean.

Upvotes: 4

daremkd
daremkd

Reputation: 8424

You can use codepoints or each_codepoint methods, for example:

old_string = 'test something'
new_string = ''

old_string.each_codepoint {|x| new_string << (x+2).chr}

p new_string #=> "vguv\"uqogvjkpi"

Upvotes: 0

Related Questions