Ruby:如何获取字符串的第一个字符 [英] Ruby: How to get the first character of a string

查看:44
本文介绍了Ruby:如何获取字符串的第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

所以如果字符串是Smith",我只想要S".

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

推荐答案

您可以使用 Ruby 的开放类使您的代码更具可读性.例如,这个:

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

将允许您对任何字符串使用 initial 方法.因此,如果您有以下变量:

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

这里提到的另一种方法在 Ruby 1.8 上不起作用(不是说你应该再使用 1.8 了!--但是当这个答案发布时它仍然很常见):

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] 

这篇关于Ruby:如何获取字符串的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆