122

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".

2
  • 11
    As a side note, if you are in Rails you can just do 'Smith'.first Aug 8, 2011 at 2:48
  • 1
    Ruby 1.9+ has "Smith".chr #=> "S" Jul 8, 2018 at 5:27

14 Answers 14

139

You can use Ruby's open classes to make your code much more readable. For instance, this:

class String
  def initial
    self[0,1]
  end
end

will allow you to use the initial method on any string. So if you have the following variables:

last_name = "Smith"
first_name = "John"

Then you can get the initials very cleanly and 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 that you should be using 1.8 anymore anyway!--but when this answer was posted it was still quite common):

puts 'Smith'[0]           # prints 83

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:

puts last_name[0,1] 
114

If you use a recent version of Ruby (1.9.0 or later), the following should work:

'Smith'[0] # => 'S'

If you use either 1.9.0+ or 1.8.7, the following should work:

'Smith'.chars.first # => 'S'

If you use a version older than 1.8.7, this should work:

'Smith'.split(//).first # => 'S'

Note that 'Smith'[0,1] does not work on 1.8, it will not give you the first character, it will only give you the first byte.

9
  • 1
    note that this only works in ruby19. in ruby18 "Smith"[0] would return the integer value of the character 'S'. Both versions obey "Smith"[0,1] == "S".
    – rampion
    Apr 28, 2010 at 15:33
  • @rampion: Sure, but there's no indication in the question that the OP doesn't use the most recent version, so why bother complicating things? Apr 28, 2010 at 15:51
  • 4
    Ruby 1.8 is not legacy! The Ruby 1.8 line is still supported and there will most likely be a 1.8.8 version released. Moreover, neither JRuby nor Rubinius yet support 1.9. I would bet 5$ that there are today far more users of 1.8 than 1.9. Apr 28, 2010 at 16:20
  • 3
    @Jörg: The answer "Smith"[0,1] does work on 1.8 (assuming ASCII). Not sure why you assume so much about the requester, as well as about everybody else who would like to learn from that question. For example, Mac OS X comes bundled with Ruby 1.8, so no installation is required for these users. Apr 28, 2010 at 17:11
  • 3
    How would you get the initial of the name 'Ångström' (in UTF-8) so that it would work as expected in both Ruby 1.8.x and 1.9.x? Neither of the suggested methods would work in 1.8.x. Apr 29, 2010 at 9:08
33
"Smith"[0..0]

works in both ruby 1.8 and ruby 1.9.

1
  • 1
    That's the best solution if 1.8.6 and 1.9 support is required.
    – plang
    Apr 21, 2011 at 11:39
28

For completeness sake, since Ruby 1.9 String#chr returns the first character of a string. Its still available in 2.0 and 2.1.

"Smith".chr    #=> "S"

http://ruby-doc.org/core-1.9.3/String.html#method-i-chr

1
  • 1
    this is exactly the kind of sneakiness i was looking for. and unlike .first, it does not require rails to work with a string.
    – omikes
    Nov 28, 2020 at 21:53
14

In MRI 1.8.7 or greater:

'foobarbaz'.each_char.first
0
14

Try this:

>> a = "Smith"
>> a[0]
=> "S"

OR

>> "Smith".chr
#=> "S"
12

In Rails

name = 'Smith'
name.first 
1
  • easy way to use. Thanks for answer.
    – AMIC MING
    Feb 13, 2017 at 22:01
5
>> s = 'Smith'                                                          
=> "Smith"                                                              
>> s[0]                                                                 
=> "S"                                                        
2
  • 1
    note that this only works in ruby19. in ruby18 "Smith"[0] would return the integer value of the character 'S'. Both versions obey "Smith"[0,1] == "S".
    – rampion
    Apr 28, 2010 at 15:32
  • 1
    @rampion: indeed. I'd add that "Smith"[0] == ?S is true on both Ruby 1.8 and 1.9 Apr 28, 2010 at 15:35
5

Another option that hasn't been mentioned yet:

> "Smith".slice(0)
#=> "S"
2

Because of an annoying design choice in Ruby before 1.9 — some_string[0] returns the character code of the first character — the most portable way to write this is some_string[0,1], which tells it to get a substring at index 0 that's 1 character long.

2
  • str[0,1] doesn't work the same in 1.8 and 1.9 either, as in the former it returns the first byte while in the latter it returns the first character. Apr 29, 2010 at 9:12
  • 1
    That's not really a difference in how the indexing works so much as in 1.9's support for multibyte languages. They're both meant to return the first character, but 1.8 has a more naive view of what a "character" is.
    – Chuck
    Apr 29, 2010 at 16:50
1

Try this:

def word(string, num)
    string = 'Smith'
    string[0..(num-1)]
end
1
  • 1
    Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
    – DCCoder
    Sep 27, 2020 at 21:13
0

If you're using Rails You can also use truncate

> 'Smith'.truncate(1, omission: '')
#=> "S"

or for additional formatting:

> 'Smith'.truncate(4)
#=> "S..."

> 'Smith'.truncate(2, omission: '.')
#=> "S."

While this is definitely overkill for the original question, for a pure ruby solution, here is how truncate is implemented in rails

# File activesupport/lib/active_support/core_ext/string/filters.rb, line 66
def truncate(truncate_at, options = {})
  return dup unless length > truncate_at

  omission = options[:omission] || "..."
  length_with_room_for_omission = truncate_at - omission.length
  stop =        if options[:separator]
      rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
    else
      length_with_room_for_omission
    end

  "#{self[0, stop]}#{omission}"
end
2
  • truncate is only available in Rails? Apr 20, 2021 at 15:59
  • @MartinThurn yes, good catch. Updated with a ruby implementation of truncate Apr 21, 2021 at 16:25
0

Other way around would be using the chars for a string:

def abbrev_name
    first_name.chars.first.capitalize + '.' + ' ' + last_name
end
-3

Any of these methods will work:

name = 'Smith'
puts name.[0..0] # => S
puts name.[0] # => S
puts name.[0,1] # => S
puts name.[0].chr # => S
1
  • 1
    None of these methods will work with that . after name. And the last one is non-sensical even if you remove the ., because it's using two different methods to do the same thing – [0] and chr().
    – jeffdill2
    Jan 8, 2018 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.