Ruby: How to get the first character of a string -
how can first character in string using ruby?
ultimately i'm doing taking someone's last name , creating initial out of it.
so if string "smith" want "s".
you can use ruby's open classes make code more readable. instance, this:
class string def initial self[0,1] end end
will allow use initial
method on string. if have following variables:
last_name = "smith" first_name = "john"
then can initials cleanly , readably:
puts first_name.initial # prints j puts last_name.initial # prints s
the other method mentioned here doesn't work on ruby 1.8 (not should using 1.8 anymore anyway!--but when answer posted still quite common):
puts 'smith'[0] # prints 83
of course, if you're not doing on regular basis, defining method might overkill, , directly:
puts last_name[0,1]
Comments
Post a Comment