覆盖字符串的一部分

时间:2012-09-24 06:23:25

标签: ruby string ruby-1.9.3

是否有一种简单的方法来覆盖字符串,如下所示,或类似的东西?

s = "123456"
r1 = "abc"
s.loverwrite(r1) # => "abc456"
s.coverwrite(r1) # => "12abc6"  (or "1abc56")
s.roverwrite(r1) # => "123abc"

r2 = "abcdefghi"
s.loverwrite(r2) # => "abcdef"
s.coverwrite(r2) # => "bcdefg"  (or "cdefgh")
s.roverwrite(r2) # => "defghi"

1 个答案:

答案 0 :(得分:1)

使用[]=非常简单:

class String
  def loverwrite(s)
    dup.tap{|result| result[0, s.length] = s[0, length]}
  end
end