使用 Ruby 显示字符串中的第一个单词

Display first Word in String with Ruby

我在 rails 上使用 ruby,我只想显示字符串的第一个单词。

我的错误代码:<%= @user.name %> 显示 Barack Obama

我想让它显示 Barack 和其他地方 Obama

如何拆分显示?

假设您有:

string = "Barack Obama"
split_string = string.split()

在 ruby 文档中:

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified.

之后使用 split_string[0] # ==> Baracksplit_string[1] # ==> Obama

简短易读:

name = "Obama Barack Hussein"
puts "#{name.partition(" ").first} - #{name.partition(" ").last}"
# Obama - Barack Hussein

如果名字和姓氏的顺序颠倒

name = "Barack Hussein Obama"
puts "#{name.rpartition(" ").last} - #{name.rpartition(" ").first}"
# Obama - Barack Hussein
> "this is ruby".split.first
#=> "this"

你可以简单:

# `split` default is split by space `' '`
<%= @user.name.split.first %>

我推荐 further reading about decorators 在这里你可以定义一个方法(或者你也可以依赖一个助手):

# It will give you 'Barack'
def first_name
  name.split.first
end

# It will give you 'Obama'
def last_name
  name.split.last
end