7

Ruby で String#gsub によって行われる置換の数をどのように制限しますか?

PHP では、置換を制限するパラメーターを受け取る preg_replace を使用してこれを簡単に行うことができますが、Ruby でこれを行う方法がわかりません。

4

4 に答える 4

5

カウンターを作成し、gsub ループ内でデクリメントできます。

str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"
于 2011-05-15T20:20:17.997 に答える
3

gsub はすべてのオカレンスを置き換えます。

String#sub を試すことができます

http://ruby-doc.org/core/classes/String.html#M001185

于 2011-05-15T16:39:46.787 に答える
3
str = 'aaaaaaaaaa'
# The following is so that the variable new_string exists in this scope, 
# not just within the block
new_string = str 
5.times do 
  new_string = new_string.sub('a', 'x')
end
于 2011-05-16T00:12:01.613 に答える