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?
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.
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.
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.
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.
> "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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With