Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby/regex getting the first letter of each word

Tags:

regex

ruby

I want to get the first letter of each word put together, making something like "I need help" turn into "Inh". I was thinking to trim everything off, then going from there, or grab each first letter right away.

like image 720
user3606254 Avatar asked May 07 '14 01:05

user3606254


People also ask

How do I get the first letter 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. The above syntax extracts the character from the index position 0 .

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

To get the first letter of each word in a string: Call the split() method on the string to get an array containing the words in the string. Call the map() method to iterate over the array and return the first letter of each word. Join the array of first letters into a string, using the join() method.

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What kind of regex does Ruby use?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.


1 Answers

You could simply use split, map and join together here.

string = 'I need help'
result = string.split.map(&:first).join
puts result  #=> "Inh"
like image 200
hwnd Avatar answered Nov 15 '22 14:11

hwnd