OneBite.Dev - Coding blog in a bite size

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

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

  string = "Hello World"
  last_char = string[-1]
  puts last_char

This code will find the last character of a string. First, the string “Hello World” is assigned to the variable ‘string’. Then the last character is found by accessing the index of the last character ‘-1’ of the string and assigning it to the ‘last_char’ variable. Lastly we use the puts method to print the value of ‘last_char’ to the console.

ruby