What is lstrip in Ruby?

Overview

lstrip in Ruby is used to remove the leading whitespace characters in a string.

A whitespace character could be a space, null, horizontal tab, line feed, vertical tab, form feed, or carriage return.

Syntax

str.lstrip

where str is the string whose leading whitespace characters we want to remove.

Parameters

This function doesn’t take any parameters.

Return value

It returns the string str with any leading whitespace characters removed.

Code example

# create strings
str1 = " Edpresso"
str2 = "is"
str3 = "\n\t\rThe"
str4 = "\Best !"
# remove leading
# whitespace characters
a = str1.lstrip
b = str2.lstrip
c = str3.lstrip
d = str4.lstrip
# print results
puts a
puts b
puts c
puts d

Explanation

  • Lines 2-5: We create some strings from which we want to remove the leading whitespace characters.

  • Lines 9-12: We use the lstrip method to remove the leading whitespace characters from the strings and store the returned values in variables a, b, c, and d.

  • Lines 15-18: We print the results to the console.

Free Resources