Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple characters in string at once

Tags:

ruby

Where as str[] will replace a character, str.insert will insert a character at a position. But it requires two lines of code:

str = "COSO17123456"
str.insert 4, "-"
str.insert 7, "-"
=> "COSO-17-123456"

I was thinking how to do this in one line of code. I came up with the following solution:

str =  "COSO17123456"
str.each_char.with_index.reduce("") { |acc,(c,i)| acc += c + ( (i == 3 || i == 5) ? "-" : "" ) }
  => "COSO-17-123456 

Is there a built-in Ruby helper for this task? If not, should I stick with the insert option rather than combining several iterators?

like image 682
Daniel Viglione Avatar asked Jun 01 '26 05:06

Daniel Viglione


1 Answers

Use each to iterate over an array of indices:

str = "COSO17123456"
[4, 7].each { |i| str.insert i, '-' }
str #=> "COSO-17-123456"
like image 105
Sagar Pandya Avatar answered Jun 04 '26 02:06

Sagar Pandya