Reputation: 892
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
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
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
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