开发者

Ruby: How to get the first character of a string

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 o开发者_C百科ut of it.

So if the string was "Smith" I just want "S".


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] 


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.


"Smith"[0..0]

works in both ruby 1.8 and ruby 1.9.


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


In MRI 1.8.7 or greater:

'foobarbaz'.each_char.first


Try this:

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

OR

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


In Rails

name = 'Smith'
name.first 


>> s = 'Smith'                                                          
=> "Smith"                                                              
>> s[0]                                                                 
=> "S"                                                        


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.


Try this:

def word(string, num)
    string = 'Smith'
    string[0..(num-1)]
end


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


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

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜