String ๐“ฏ operations using Ruby ๐Ÿ’Žmethods

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).
  • .reverse reverses their order.
  • .join merges 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):

  1. Ignore dots (.) in the username part.
  2. Remove everything after a plus (+) in the username.
  3. 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("+").first keeps 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.. ๐Ÿš€