How to get the first character of a string in Ruby
In this tutorial, we are going to learn about how to get the first character of a given string in Ruby.
Consider, we have the following string:
name = "Pearson"Now, we want to get the first character P from the above string.
Using the chr method
In Ruby, we can use the built-in chr method to access the first character of a string.
Here is an example:
name = "Pearson"
firstChar = name.chr
puts firstCharOutput:
"P"Similarly, we can also use the subscript syntax [0] to get the first character of a string.
name = "Pearson"
firstChar = name[0]
puts firstCharThe above syntax extracts the character from the index position 0.


