×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby program to get the index of the substring in a string

Last Updated : December 15, 2025

Problem Solution

In this program, we will create two strings and get the index of the specified substring in the string using the index() method.

Program/Source Code

The source code to get the index of the substring in a string is given below. The given program is compiled and executed successfully.

# Ruby program to get the index of 
# substring from a string

str = "Hello India";
substr1="India";
substr2="World";

index = str.index(substr1);

if index != nil
    print "String found at index ",index,"\n";
else
    print "String not found\n";
end

index = str.index(substr2);

if index != nil
    print "String found at index ",index,"\n";
else
    print "String not found\n";
end

Output

String found at index 6
String not found

Explanation

In the above program, we created two string variables str, substr1, substr2 that are initialized with "Hello India", "India", "World". Then we used the index() method to check the string containing specified substring and print the appropriate message.

Ruby Strings Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.