To trim a string in Ruby, you can use the strip
, lstrip
, and rstrip
methods of the String class.
In this example,
" Hello World "
to the variable str1
.strip
method on str1
to remove leading and trailing whitespace characters.str1 = " Hello World "
trimmed_str1 = str1.strip
puts "Trimmed string is: '#{trimmed_str1}'"
Trimmed string is: 'Hello World'
In this example,
" apple"
to the variable str2
.lstrip
method on str2
to remove leading whitespace characters.str2 = " apple"
trimmed_str2 = str2.lstrip
puts "Trimmed string is: '#{trimmed_str2}'"
Trimmed string is: 'apple'
In this example,
"banana "
to the variable str3
.rstrip
method on str3
to remove trailing whitespace characters.str3 = "banana "
trimmed_str3 = str3.rstrip
puts "Trimmed string is: '#{trimmed_str3}'"
Trimmed string is: 'banana'
In this tutorial, we learned How to Trim a String in Ruby language with well detailed examples.