1

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.

2
  • 2
    Why? We very seldom need to operate at that level in Ruby, so it sounds like you're trying to accomplish something in a very C++ way that we'd do entirely differently in Ruby. Explain what data you're working with, and why, and we can probably show you the Ruby way to do it, not show you the C++ way to do it in Ruby. Commented Jan 5, 2014 at 3:41
  • @theTinMan Tin Man Thanks for asking about the purpose. I updated my question. Commented Jan 5, 2014 at 3:47

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice solution, Sn, even if you wanted to convert the space: tr('a-z ', 'c-zab\"')
It's not necessary to escape the double-quote when it's enclosed in single quotes: ' '.tr(' ', '"') # => "\"".
1

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"

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.