Scott Watermasysk
Ruby Sub vs. Gsub
A little Ruby distinction I had not seen (or remembered seeing) before.
In Ruby, both String#sub
and String#gsub
are methods used for string substitution, but they have a subtle difference:
String#sub
: This method performs a substitution based on a regular expression pattern, replacing only the first occurrence that matches the pattern.
str = "hello world"
new_str = str.sub(/o/, "a")
puts new_str
Output: hella world
String#gsub
: This method also performs a substitution based on a regular expression pattern, but it replaces all occurrences that match the pattern within the string.
str = "hello world"
new_str = str.gsub(/o/, "a")
puts new_str
Output: hella warld
Hat tip to ChatGPT, who answered this question for me.