Examples of String Functions in Ruby

RubyServer Side ProgrammingProgramming

In this article, we will explore some useful string functions in Ruby that are widely used to format data.

Get the Length of the String

To find the length of the string, we will use the size method.

Example

Consider the code shown below.

str = "TutorialsPoint"
puts str.size

Output

It will produce the following output.

14

To Check Empty string

To check if a string is empty, we use the size method and comparison operator.

Example

Consider the code shown below.

str = "TutorialsPoint"
puts str.size == 0

Output

It will produce the following output.

false

To Extract a Substring from String

To extract a substring from a string, we will use square bracket notation.

Example

Consider the code shown below.

str = "TutorialsPoint"
puts str[1,3]

Output

It will produce the following output.

uto

Check if a String Contains a Substring

To check if a string contains a substring, we will use include method.

Example

Consider the code shown below.

str = "TutorialsPoint"
puts str.include?("ials")

Output

When we execute this code, it will produce the following output

true

hex Method

In Ruby, hex method is used to treat the leading characters from the given string as a string of hexadecimal digits and the corresponding number. It returns "0" (zero) on error.

Example

Consider the code shown below.

str = "TutorialsPoint"
puts str.hex

another_str = "12345"
puts another_str.hex

Output

It will produce the following output.

0
74565

each_byte Method

In Ruby, the each_byte method is used to pass each byte in a string to the given block, or to return an enumerator if no block is specified.

Example

Consider the code shown below.

str = "TutorialsPoint"
puts str.each_byte{|b| print b, ' ' }

another_str = "TextString"
puts another_str.each_byte{|b| print b, ' ' }

Output

It will produce the following output.

84 117 116 111 114 105 97 108 115 80 111 105 110 116 TutorialsPoint
84 101 120 116 83 116 114 105 110 103 TextString
raja
Updated on 12-Apr-2022 07:56:32

Advertisements