How to concatenate first alphabets from a sentence containing few words. Is there a ruby function which can be used from the language?
1. foo bar
2. foo bar caz
3. foo
4. foo d bar
should result in
1. fb
2. fb
3. f
4. fd
CodePudding user response:
Assuming the input is test_string
and you want the first letter of each word in a sentence try:
test_string.split.map{|f| f.chars.first}.join
Looking at your output, you seem to only want this for the first two words in the sentence:
test_string.split.take(2).map{|f| f.chars.first}.join
CodePudding user response:
Just some feedback first on asking questions on S.O. It would be nice to know how you expect the 'foo bar' strings to come in. Do they come in as strings, separated? Are they all in an array? Is this just a challenge you're working on in a bootcamp or something similar? Is the expected output for the #4 on the last four strings a typo? Shouldn't it be 'fdb'?
Without those questions answered, I will assume the following: 1) the first 4 strings are separated and can be set to variables OR they are all in an array, separated by ',', 2) you want your output to be an array containing the last 4 strings, separated by ',', and 3) the 'foo d bar' gives you a 'fd' cause you only want the first letter of each "word", up to 2 letters.
Here is one solution...
strings = ['foo bar', 'foo bar caz', 'foo', 'foo d bar']
new_array = []
strings.each do |word|
words = word.split(' ')[0..1]
words[1] ? new_array << "#{words[0][0]}#{words[1][0]}" : new_array << "#{words[0][0]}"
end