简体   繁体   中英

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 out 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]

适用于 ruby​​ 1.8 和 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

在 MRI 1.8.7 或更高版本中:

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

由于 1.9 之前的 Ruby 中的一个令人讨厌的设计选择—— some_string[0]返回第一个字符的字符代码——编写它的最便携的方法是some_string[0,1] ,它告诉它在索引 0 处获取一个子字符串,即1 个字符长。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM