Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display first Word in String with Ruby

Tags:

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?

like image 485
DanielsV Avatar asked Jun 05 '15 19:06

DanielsV


People also ask

How do you get the first word of a string in Ruby?

In Ruby, we can use the built-in chr method to access the first character of a string. Similarly, we can also use the subscript syntax [0] to get the first character of a string.

How do you find the part of a string in Ruby?

A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.

How do you split a word in Ruby?

The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.

How do you split a character in a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


2 Answers

> "this is ruby".split.first #=> "this" 
like image 107
chad_ Avatar answered Sep 25 '22 02:09

chad_


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 
like image 45
peter Avatar answered Sep 21 '22 02:09

peter