Reputation: 17
If I have a string "hello", how would I add characters between each character in the string so it would look like "h--e--l--l--o"
Upvotes: 0
Views: 1543
Reputation: 110665
You can do that without converting the string to an array by using String#gsub with a regular expression:
"hello".gsub(/(?<=.)(?=.)/, '--')
#=> "h--e--l--l--o".
(?<=.)
is a positive lookbehind, asserting that the match is preceded by a character and (?=.)
is a positive lookahead, asserting that the match is followed by a character. Note that matches are zero-width; it is the locations between consecutive characters that are matched.
Upvotes: 3
Reputation: 425
There are many solutions to this, I would suggest the following :
1/ split the string into an array
of individual characters with chars
"hello".chars
=> ["h", "e", "l", "l", "o"]
2/ join
them with the two characters you want to add in-between each character
["h", "e", "l", "l", "o"].join('--')
=> "h--e--l--l--o"
You can execute this in one line as such :
"hello".chars.join('--')
Upvotes: 2