To get a character at a specific index in a string in Ruby, you can use array-like indexing or the []
operator.
If given string is in x
and we would like to access character at index i
, then the expression x[i]
returns the required character.
In this example,
str
with a value of "Hello World"
.[]
operator on the string str
.str = "Hello World"
char_at_index_4 = str[4]
puts "Character at index 4: #{char_at_index_4}"
Character at index 4: o
In this example,
str
with a value of "Ruby"
.[]
operator on the string str
.str = "Ruby"
char_at_index_1 = str[1]
puts "Character at index 1: #{char_at_index_1}"
Character at index 1: u
In this tutorial, we learned how to get Character at Specific Index in String in Ruby language using array-like indexing, with well detailed examples.