In MRI 1.8.7 or greater:
'foobarbaz'.each_char.first
Another option that hasn't been mentioned yet:
> "Smith".slice(0)
#=> "S"
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.
>> s = 'Smith'
=> "Smith"
>> s[0]
=> "S"
You can also use truncate
> 'Smith'.truncate(1, omission: '')
#=> "S"
or for additional formatting:
> 'Smith'.truncate(4)
#=> "S..."
> 'Smith'.truncate(2, omission: '.')
#=> "S."
In Rails
name = 'Smith'
name.first
"Smith"[0..0]
works in both ruby 1.8 and ruby 1.9.
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.
Try this:
>> a = "Smith"
>> a[0]
=> "S"
OR
>> "Smith".chr
#=> "S"
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
Try this:
def word(string, num)
string = 'Smith'
string[0..(num-1)]
end
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"
Source: Stackoverflow.com