简体   繁体   中英

Display first Word in String with Ruby

I'm using ruby on rails and I want to display only first word of string.

My broken code: <%= @user.name %> displaying Barack Obama .

I would want to have it display Barack and in other place 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:

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.

after that use 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

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