Replace random instance of substring inside a string (ruby) -
Replace random instance of substring inside a string (ruby) -
i want instances of given substring within string, , replace randomly: not in every instance of it, esporadically. thinking of using .each method each instance of substring, , within code block using rand replace or not depending on result. bit stuck how implement .each method in situation. can help? (i using ruby 1.9)
you can utilize block-variant of string#gsub
:
s = 'foo bar foo bar foo bar foo bar' # , want alter random instances of "foo" "baz": s.gsub(/foo/){|m| rand(2) == 0 ? 'baz' : m} #=> "baz bar foo bar baz bar foo bar"
ruby
Comments
Post a Comment