OneBite.Dev - Coding blog in a bite size

find the first occurrence of a character in a string in Ruby

Code snippet on how to find the first occurrence of a character in a string in Ruby

  def find_first_occurrence(string, char)
    string.index(char)
  end

This code is written in the Ruby programming language and is used to find the first occurrence of a character in a string. The code defines a function named “find_first_occurrence” that takes two parameters, the string and the character to search for. The function then uses the built-in index function to find the first occurrence of the character in the string. If the character is found, the index (position) of the character in the string is returned, otherwise nil is returned. For example, if we were to call the function with a string “Hello world” and the character “o”, the index of the first “o” in the string (4) would be returned.

ruby