To get the first character of a string in Ruby, you can use array-like indexing or the []
method.
If given string is in variable x
and we would like to access the first character in the string, then the expression x[0]
returns the first character.
In this example,
str
with a value of "Hello World"
.0
on the string str
or the []
method with index 0
to get the first character.str = "Hello World"
first_char = str[0]
puts "First character: #{first_char}"
First character: H
In this example,
str
with a value of "apple"
.0
on the string str
or the []
method with index 0
to get the first character.str = "apple"
first_char = str[0]
puts "First character: #{first_char}"
First character: a
In this tutorial, we learned How to get First Character in String in Ruby language using array-like indexing, and index=0, with well detailed examples.