← Back to Ruby Course | Chapter 3: Strings | Lesson 5 of 7

gsub और sub

sub और gsub text में एक pattern ढूंढते हैं और इसे किसी दूसरी चीज़ से swap करते हैं, एक document में Find and Replace की तरह। sub सिर्फ पहला match बदलता है, जबकि gsub सबको बदलता है।

In this page:

  1. gsub और sub
Syntax
ruby
string.sub(pattern, replacement)
string.gsub(pattern, replacement)

gsub और sub

sub(pattern, replacement) एक string में एक pattern का पहला match replace करता है, और gsub() हर match replace करता है (global substitute)।

दोनों pattern की तरह या तो एक literal string या एक regular expression accept करते हैं, और एक block form आपको replacement dynamically compute करने देता है। ज़्यादातर Ruby string methods की तरह, ये एक नई string return करते हैं जब तक आप ! version (gsub!) इस्तेमाल न करें।

Note: gsub एक block form accept करता है, जैसे text.gsub(/\\d+/) { |n| n.to_i * 2 }, आपको हर replacement dynamically compute करने देते हुए।

उदाहरण: gsub and sub

markup
text = "cat bat cat sat"

puts text.sub("cat", "dog")
puts text.gsub("cat", "dog")
puts text.gsub(/[aeiou]/, "*")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. sub इस्तेमाल करना और सारे matches बदलने की उम्मीद करना, जब सिर्फ पहला बदलता है; gsub इस्तेमाल करें।
  2. यह उम्मीद करना कि text.gsub(...) text बदल देगा, जब यह एक नई string return करता है जब तक आप gsub! इस्तेमाल न करें।
  3. regex symbols वाली एक string को एक pattern की तरह इस्तेमाल करना, जैसे ".", जो एक regex में किसी भी character से match करता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.