How to remove leading and trailing whitespaces (trim) from a string in Ruby

2 Answers

0 votes
# Removes leading and trailing whitespace from a string.
#
# @param text [String] The input string.
# @return [String] A new string with surrounding whitespace removed.
def trim_whitespace(text)
  text.strip
end

# Example usage
input = "   Hello, Ruby!   "
result = trim_whitespace(input)

puts "Original: '#{input}'"
puts "Trimmed: '#{result}'"


# run:
# 
# Original: '   Hello, Ruby!   '
# Trimmed: 'Hello, Ruby!'
#


 



answered 5 hours ago by avibootz
0 votes
# Removes leading and trailing whitespace from a string in place.
#
# @param text [String] The string to modify.
# @return [String, nil] The modified string, or nil if no changes were made.
def trim_whitespace!(text)
  text.strip!
end

input = "   Hello, Ruby!   "
trim_whitespace!(input)

puts "'#{input}'"


# run:
# 
# 'Hello, Ruby!'
#


 



answered 5 hours ago by avibootz
...