Reputation:
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
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
Reputation: 28606
I'd just use gsub to find and double them.
"abc def".gsub(/\b\w/, '\0\0')
=> "aabc ddef"
Upvotes: 4
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