String#slice! 和String#insert 将让您更接近您想要的,而无需将您的字符串转换为数组。
例如,要模拟Array#pop,你可以这样做:
text = '¡Exclamation!'
mark = text.slice! -1
mark == '!' #=> true
text #=> "¡Exclamation"
同样,对于Array#shift:
text = "¡Exclamation!"
inverted_mark = text.slice! 0
inverted_mark == '¡' #=> true
text #=> "Exclamation!"
当然,要执行Array#push,您只需使用其中一种连接方法:
text = 'Hello'
text << '!' #=> "Hello!"
text.concat '!' #=> "Hello!!"
要模拟Array#unshift,请改用String#insert,这很像切片的倒数:
text = 'World!'
text.insert 0, 'Hello, ' #=> "Hello, World!"
您还可以使用 slice 以多种方式从字符串中间抓取块。
首先你可以传递一个起始位置和长度:
text = 'Something!'
thing = text.slice 4, 5
您还可以传递 Range 对象来获取绝对位置:
text = 'This is only a test.'
only = text.slice (8..11)
在 Ruby 1.9 中,像这样使用 String#slice 与 String#[] 相同,但如果您使用 bang 方法 String#slice! 它实际上会删除您指定的子字符串。
text = 'This is only a test.'
only = text.slice! (8..12)
text == 'This is a test.' #=> true
这里有一个稍微复杂一点的例子,我们重新实现了一个简单版本的String#gsub! 来进行搜索和替换:
text = 'This is only a test.'
search = 'only'
replace = 'not'
index = text =~ /#{search}/
text.slice! index, search.length
text.insert index, replace
text == 'This is not a test.' #=> true
当然,在 99.999% 的情况下,您会想要使用前面提到的 String.gsub!,它会做同样的事情:
text = 'This is only a test.'
text.gsub! 'only', 'not'
text == 'This is not a test.' #=> true
参考: