How can I get the first character in a string using Ruby?
Ultimately what I’m doing is taking someone’s last name and just creating an initial out of it.
So if the string was “Smith” I just want “S”.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use Ruby’s open classes to make your code much more readable. For instance, this:
will allow you to use the
initialmethod on any string. So if you have the following variables:Then you can get the initials very cleanly and readably:
The other method mentioned here doesn’t work on Ruby 1.8 (not that you should be using 1.8 anymore anyway!–but when this answer was posted it was still quite common):
Of course, if you’re not doing it on a regular basis, then defining the method might be overkill, and you could just do it directly: