简体   繁体   English

用Ruby显示字符串中的第一个Word

[英]Display first Word in String with Ruby

I'm using ruby on rails and I want to display only first word of string. 我在rails上使用ruby,我只想显示字符串的第一个单词。

My broken code: <%= @user.name %> displaying Barack Obama . 我破碎的代码: <%= @user.name %>显示Barack Obama

I would want to have it display Barack and in other place Obama . 我想让它展示Barack和其他地方的Obama

How can I split it and display it? 我该如何拆分并显示它?

> "this is ruby".split.first
#=> "this"

Short and readable: 简短易读:

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

and if the order of the first and lastname is reversed 如果第一个和最后一个名字的顺序颠倒过来

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

Lets said you have: 让我们说你有:

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

In ruby documentation: 在ruby文档中:

If pattern is omitted, the value of $; 如果省略pattern,则$;的值; is used. 用来。 If $; 如果$; is nil (which is the default), str is split on whitespace as if ` ' were specified. 是nil(这是默认值),str在空格上分割,就像指定了`'一样。

after that use split_string[0] # ==> Barack ou split_string[1] # ==> Obama 之后使用split_string[0] # ==> Barack ou split_string[1] # ==> Obama

You can simple: 你可以简单:

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

I recommend further reading about decorators where you can define a method like (or you can rely on a helper as well): 我建议您进一步阅读有关装饰器的内容 ,您可以在其中定义类似的方法(或者您也可以依赖帮助器):

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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