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"
2 Answers
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.
Comments
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('--')
'hello'could be converted to'h-e-l-l-o-', not to'h-e-l-l-o', a signficant different. I suggest it be reopened until a suitable dup reference is found.