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.. ๐Ÿš€

Programming in Python: Strings

Strings are a fundamental data type in Python and can be manipulated in various ways. Strings are enclosed within either single ('), double ("), or triple (''' or “””) quotes. Triple quotes allow for multi-line strings.

Assigning and Printing Strings

We can assign a string to a variable and print it using the print function.

# Assigning a string
greeting = 'Hello, World!'

# Printing a string
print(greeting)

Output:

Hello, World!

String Concatenation

Strings can be concatenated using the + operator:

print("Hello" + " World")

Output:

Hello World

String Slicing

Python allows slicing strings using indices. The slice notation follows the format string[start:end], where start is inclusive, and end is exclusive.

string1 = 'hello world'

print(string1[0:1])  # 'h'
print(string1[0:4])  # 'hell'
print(string1[2:4])  # 'll'
print(string1[:4])   # 'hell'
print(string1[3:])   # 'lo world'

Attempting to modify a string using slicing will result in an error because strings in Python are immutable:

string1[:0] = 'Hai'  # TypeError: 'str' object does not support item assignment

However, we can create a new string using concatenation:

print('Hai' + string1[:])  # 'Haihello world'

Using Negative Indices

Negative indices allow accessing elements from the end of the string.

print(string1[-1])    # 'd'
print(string1[-4:-1]) # 'orl'
print(string1[-4:-2]) # 'or'

If the slicing range is incorrect, it may return an empty string:

print(string1[-4:0])   # ''
print(string1[-1:-4])  # ''
print(string1[-11:-1]) # 'hello worl'

Additional String Methods

Python provides several useful methods for string manipulation:

s = " Python Programming "

print(s.lower())       # ' python programming '
print(s.upper())       # ' PYTHON PROGRAMMING '
print(s.strip())       # 'Python Programming' (removes leading/trailing spaces)
print(s.replace("Python", "Ruby"))  # ' Ruby Programming '
print(s.split())       # ['Python', 'Programming'] (splits by whitespace)

String Formatting

Python supports f-strings (introduced in Python 3.6) for formatting strings:

name = "Alice"
age = 30

print(f"My name is {name} and I am {age} years old.")

Output:

My name is Alice and I am 30 years old.

Conclusion

Python provides powerful ways to manipulate strings using slicing, concatenation, and various built-in methods. Understanding these techniques helps in efficient string handling in real-world applications.