जवाबों:
gवैश्विक के लिए खड़ा है, के रूप में विश्व स्तर पर (सभी) की जगह:
Irb में:
>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"
replaceऔर कहता है replaceAll। लेकिन रूबी की जड़ें पर्ल में हैं जो gसंशोधक का उपयोग करती हैं। यह उन चीजों में से एक है।
subबहुत तेजी से है gsub, वहाँ एक बेंचमार्क यहाँ है github.com/JuanitoFatas/fast-ruby/blob/master/code/string/...
A, sentence, separated, by, commas".gsub!(/(.*),(.*)/,"\\2 \\1") => " commas A, sentence, separated, by" कोई भी विचार क्यों gsub!केवल regex समूहों का उपयोग करते समय केवल पहले उदाहरण को खोजने / बदलने के लिए प्रतीत होता है?
अंतर यह है कि subकेवल निर्दिष्ट पैटर्न की पहली घटना को प्रतिस्थापित gsubकरता है , जबकि यह सभी घटनाओं के लिए होता है (अर्थात, यह वैश्विक रूप से बदलता है)।
subऔर gsubक्रमशः पहले और सभी मैचों का प्रतिस्थापन करें।
sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)
gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)
sub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )
##"An Introduction to R Software Course will be of 8 weeks duration"
gsub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )
##"An Introduction to R Software Course will be of 8 weeks duration"