简体   繁体   中英

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.

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.

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"

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM