Given a sequence of inclusive string indexes,
str_indices = [[1,2],[7,8]],
what's the best way to exclude these from a string?
For example, given the above indices marked for exclusion and the string happydays
, I'd like hpyda
to be returned.
Using Ranges:
str_indices=[[1,2],[7,8]]
str="happydays"
str_indices.reverse.each{|a| str[Range.new(*a)]=''}
str
=> "hpyda"
If you don't want to modifty the original:
str_indices.reverse.inject(str){|s,a|(c=s.dup)[Range.new(*a)]='';c}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With