Let’s find out solutions to some ruby coding problems that can help us to manipulate over a String in Ruby.
Learn About the following topics to solve the below problems:
Ruby String scan: https://railsdrop.com/2012/07/07/ruby-string-method-scan/
🧪 Q1: Ruby String Manipulation
❓ Prompt:
Write a method reverse_words that takes a string and returns a new string where the order of words is reversed, but the characters within each word stay in the same order.
Words are separated by spaces. Preserve exact spacing between words (multiple spaces too).
Examples:
reverse_words("hello world") #=> "world hello"
reverse_words(" good morning ruby ") #=> " ruby morning good "
✏️ Answer:
def reverse_words(str)
str.scan(/\s+|\S+/).reverse.join
end
Explanation:
str.scan(/\s+|\S+/)splits the string into tokens that are either a word or a space block (preserves exact spacing)..reversereverses their order..joinmerges them back into a single string.
Sample Test Cases:
puts reverse_words("hello world") # => "world hello"
puts reverse_words(" good morning ruby ") # => " ruby morning good "
puts reverse_words("one") # => "one"
puts reverse_words("") # => ""
🧪 Q2: Normalize Email Addresses
❓ Prompt:
Write a method normalize_email that normalizes email addresses using the following rules (similar to Gmail):
- Ignore dots (
.) in the username part. - Remove everything after a plus (
+) in the username. - Keep the domain part unchanged.
The method should return the normalized email string.
Examples:
normalize_email("john.doe+work@gmail.com") # => "johndoe@gmail.com"
normalize_email("alice+spam@company.org") # => "alice@company.org"
normalize_email("bob.smith@domain.co.in") # => "bobsmith@domain.co.in"
✏️ Answer:
def normalize_email(email)
local, domain = email.split("@")
local = local.split("+").first.delete(".")
"#{local}@#{domain}"
end
Explanation:
split("@")separates username from domain.split("+").firstkeeps only the part before+..delete(".")removes all dots from the username.- Concatenate with the domain again.
Test Cases:
puts normalize_email("john.doe+work@gmail.com") # => "johndoe@gmail.com"
puts normalize_email("alice+spam@company.org") # => "alice@company.org"
puts normalize_email("bob.smith@domain.co.in") # => "bobsmith@domain.co.in"
puts normalize_email("simple@domain.com") # => "simple@domain.com"
to be continued.. 🚀