Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing characters by index from Ruby String

Tags:

string

ruby

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.

like image 615
mbm Avatar asked Dec 28 '22 22:12

mbm


1 Answers

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}
like image 124
AShelly Avatar answered Jan 11 '23 12:01

AShelly