user7055375
user7055375

Reputation:

How do I repeat the first character of words in a string?

Using Ruby 2.4. I have a string with letters and spaces. For example,

"abc def"

How do I change the string such that I duplicate the first character of each word? That is, the above would become:

"aabc ddef"

because "a" and "d" are the start of the words in the above string. By word, I mean any sequence of characters separated by spaces.

Upvotes: 0

Views: 166

Answers (3)

Raga
Raga

Reputation: 136

You can try the below snippet

str = "abc def"
index = 0
new_str = ""

str.split.each do | string |
    string = string[0] + string
    new_str = new_str + string + " "
    index = index + 1
end

puts "New string #{new_str}"

Upvotes: 0

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

I'd just use gsub to find and double them.

"abc def".gsub(/\b\w/, '\0\0')
=> "aabc ddef"

Upvotes: 4

Sebastián Palma
Sebastián Palma

Reputation: 33430

You can just split the string by each space, and multiply the first character the number of times you need, then append, or concatenate the "initial" word:

p "abc def".split.map { |word| "#{word[0] * 10}#{word}" }.join(' ')

Upvotes: 0

Related Questions