Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Insert Multiple Values Into String

Tags:

string

ruby

Suppose we have the string "aaabbbccc" and want to use the String#insert to convert the string to "aaa<strong>bbb</strong>ccc". Is this the best way to insert multiple values into a Ruby string using String#insert or can multiple values simultaneously be added:

string = "aaabbbccc"
opening_tag = '<strong>'
opening_index = 3
closing_tag = '</strong>'
closing_index = 6
string.insert(opening_index, opening_tag)
closing_index = 6 + opening_tag.length # I don't really like this
string.insert(closing_index, closing_tag)

Is there a way to simultaneously insert multiple substrings into a Ruby string so the closing tag does not need to be offset by the length of the first substring that is added? I would like something like this one liner:

string.insert(3 => '<strong>', 6 => '</strong>') # => "aaa<strong>bbb</strong>ccc"
like image 994
Powers Avatar asked Jul 19 '26 12:07

Powers


2 Answers

Let's have some fun. How about

class String
  def splice h
    self.each_char.with_index.inject('') do |accum,(c,i)|
      accum + h.fetch(i,'') + c
    end  
  end  
end  

"aaabbbccc".splice(3=>"<strong>", 6=>"</strong>")
=> "aaa<strong>bbb</strong>ccc"

(you can encapsulate this however you want, I just like messing with built-ins because Ruby lets me)

like image 146
roippi Avatar answered Jul 22 '26 03:07

roippi


How about inserting from right to left?

string = "aaabbbccc"
string.insert(6, '</strong>')
string.insert(3, '<strong>')
string # => "aaa<strong>bbb</strong>ccc"
like image 37
falsetru Avatar answered Jul 22 '26 02:07

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!