2014-10-08 57 views
0

我想從字符串中獲取字符窗口。Ruby返回給定字符串索引的字符窗口

s="ABCDEFGH" 

給出字符串的索引4,我想 CDEFG即兩個字符的左側和兩個字符得到字符的索引位置的右側。

所以我寫了這個。

s[0..4][-3,2] + s[4,3] #=>"CDEFG" 

但這並不覺得很地道,是有點「hackish的」,有沒有更好的,更概括的方式做到這一點?

回答

1
class String 
    def slice_with_index_and_around_chars(index, around) 
    str_range = (index - around..index + around) 
    self[str_range] 
    end 
end 

s = "ABCDEFGH" 
p s.slice_with_index_and_around_chars(4, 2) #=>"CDEFG" 
2

如果你只是想離開和指數的權這兩個人物,剛剛獲得直接:

s = "ABCDEFGH" 
index = 4 
s[index - 2, 5] # Get 5 characters starting 2 before the given index - 2 before + index + 2 after = 5 
# => "CDEFG"