How to Check if a Ruby String Has a Substring

The Ruby string class comes with dozens of built-in methods for performing common operations and queries upon strings of text. However, no method exists with the name "contains" or "search" that would imply the ability to search for and find substrings, such as the word "Hello" within the String "Hello World." The functionality is there, of course, but it is masked under the innocuous-sounding method "index."

Instructions

    • 1

      Open your terminal or command prompt. In Windows XP, do this by clicking "Start," and then "Run," and finally typing "cmd." In later versions of Windows, you would click the Windows icon button instead, and simply type "cmd" into the search bar and press "Enter."

    • 2

      Type "irb" to load the Ruby interactive interpreter.

    • 3

      Type "s = 'Hello World.'" to define a new string of text in Ruby.

    • 4

      Now type the following two commands to see how the "index" method helps you determine if a substring exists within a Ruby string:

      s.index 'World'

      s.index 'Bob'

      The first command will return '6,' the index of the first letter of the searched for string. On the other hand, the second command will return 'nil,' to indicate that the word "Bob" occurs nowhere within the string.

Tips & Warnings

  • Ruby, like most languages, has more than one way to solve a problem. The "count" method can also be used to count the number of times the substring occurs. If the result is 0, the substring does not exist. Otherwise, it does.

  • If you are familiar with Regex, you can provide regular express patterns as input to the index function. For example, the command "s.index /[aeiou]/" would search for any of the vowels anywhere in the string.

Related Searches:

References

Comments

You May Also Like

  • How to Compare Strings in Ruby

    Ruby is an extremely powerful programming/scripting language. With powerful capabilities and an efficient syntax, many things are possible with Ruby. This article...

Related Ads

Featured