String Manipulation and Reversal

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.

input_str = "Hello neat rubyists_123"

# Split the string into an array of words
words = input_str.split

puts words.inspect

This will output:

["Hello", "neat", "rubyists_123"]

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.

# Reverse each word
reversed_words = words.map { |word| word.reverse }

puts reversed_words.inspect

This produces:

["olleH", "taen", "321_stisybur"]

Step 3: Joining the Reversed Words

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