Introduction

Hello, and welcome! Are you ready to enhance your string manipulation skills with Ruby?

Today, we’ll tackle a fun and practical task: reversing the characters in each word of a string while maintaining the original word order. This exercise will deepen your understanding of Ruby string methods and sharpen your problem-solving skills. Let’s get started!

Task Statement and Description

The goal is to write a Ruby method that takes a string as input, reverses each word within the string, and returns a new string with the reversed words in their original order.

Here’s what you need to know:

  • The input string will have between 1 and 100 words.
  • Words are separated by single spaces and consist of characters ranging from a to z, A to Z, 0 to 9, or underscores _.
  • There will be no leading or trailing spaces, and double spaces won’t appear.
  • The returned string should contain the reversed words in their original order, separated by single spaces.

Example

If the input string is "Hello neat rubyists_123", the function should:

  1. Reverse "Hello" to "olleH", "neat" to "taen", and "rubyists_123" to "321_stisybur".
  2. Combine these reversed words into a single string, producing "olleH taen 321_stisybur".

Try solving the problem on your own first! Once you're ready, we’ll walk through the solution step by step and break it down together.

Step 1: Splitting the String into Words

The first step is to break the input string into words. Ruby’s split method is perfect for this, as it divides the string based on spaces by default and returns an array of words.

This will output:

Step 2: Reversing Each Word

Once the words are separated, we can reverse each one. Ruby’s reverse method makes this easy. Using map, we can apply reverse to every word in the array.

This produces:

Step 3: Joining the Reversed Words

The final step is to combine the reversed words back into a single string. Ruby’s join method allows us to do this while specifying a separator—in this case, a single space (' ').

This outputs:

Complete Method

Now, let’s bring everything together into a reusable method:

This method is concise, efficient, and adheres to Ruby best practices.

Lesson Summary

Great job! You’ve just learned how to reverse characters in each word of a string while maintaining the original word order. By combining Ruby’s split, map, and join methods, you’ve created a powerful tool for string manipulation.

Remember, the key to mastery is regular practice. Therefore, take a moment to explore related problems and practice what you’ve learned. It's all part of the joy of learning!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal