Ruby: 如何获取字符串的第一个字符

如何使用 Ruby 获得字符串中的第一个字符?

最终我要做的就是取一个人的姓然后在上面写一个首字母。

所以如果字符串是“ Smith”我只需要“ S”。

156021 次浏览
>> s = 'Smith'
=> "Smith"
>> s[0]
=> "S"

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

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

如果您使用1.9.0 + 或1.8.7,以下代码应该可以工作:

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

如果你使用的版本早于1.8.7,这个应该可以:

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

注意,'Smith'[0,1]在1.8上做 没有工作,它将 没有给你第一个字符,它将只给你第一个 字节

你可以使用 Ruby 的开放类来使你的代码更具可读性:

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

将允许您对任何字符串使用 initial方法:

last_name = "Smith"
first_name = "John"

然后你就可以很清楚地看到首字母了:

puts first_name.initial   # prints J
puts last_name.initial    # prints S

这里提到的另一个方法不能在 Ruby 1.8上工作(不是说你应该再使用1.8了!——但是当这个答案被发布出来的时候,它仍然很普遍) :

puts 'Smith'[0]           # prints 83

当然,如果你不是经常这样做,那么定义方法可能有点过了,你可以直接这样做:

puts last_name[0,1]

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.

"Smith"[0..0]

Ruby 1.8和 Ruby 1.9都可以使用。

核磁共振成像1.8.7或以上:

'foobarbaz'.each_char.first

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

试试这个:

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

或者

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

在 Rails

name = 'Smith'
name.first

这些方法中的任何一种都会奏效:

name = 'Smith'
puts name.[0..0] # => S
puts name.[0] # => S
puts name.[0,1] # => S
puts name.[0].chr # => S

Another option that hasn't been mentioned yet:

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

如果使用 Rails,也可以使用 truncate

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

或其他格式:

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


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

虽然这对于最初的问题来说显然有些夸张,但是对于纯 ruby解决方案来说,以下是 truncate如何在 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

Try this:

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

Other way around would be using the 查尔斯 for a string:

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