DanielsV
DanielsV

Reputation: 892

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?

Upvotes: 25

Views: 19432

Answers (4)

chad_
chad_

Reputation: 3819

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

Upvotes: 50

peter
peter

Reputation: 42182

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

Upvotes: 21

Brenno Costa
Brenno Costa

Reputation: 172

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

Upvotes: 1

nbeck
nbeck

Reputation: 159

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

Upvotes: 3

Related Questions