mbm mbm - 16 days ago 6
Ruby Question

Removing characters by index from Ruby String

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.

Answer

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}
Comments