Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `gsub!` return `nil`?

Tags:

string

ruby

gsub

I am using a hash map to advance the character by position: "a" into "b", etc., and to capitalize vowels.

def LetterChanges(str)
  str.to_s
  puts str
  h = ("a".."z").to_a
  i = ("b".."z").to_a.push("a")
  hash = Hash[h.zip i]
  new_str = str.downcase.gsub(/[a-z]/,hash)
  new_str.gsub!(/[aeiou]/) {|n| n.upcase }
end

LetterChanges("hello world")
LetterChanges("sentence")
LetterChanges("replace!*")
LetterChanges("coderbyte")
LetterChanges("beautiful^")
LetterChanges("oxford")
LetterChanges("123456789ae")
LetterChanges("this long cake@&")
LetterChanges("a b c dee")
LetterChanges("a confusing /:sentence:/[ this is not!!!!!!!~")

The above code works as expected except for the examples "replace!*" and "123456789ae", for which it returns nil. Why is this?

like image 919
Chris B Avatar asked Jun 11 '15 12:06

Chris B


People also ask

What does GSUB return?

gsub (s, pattern, repl [, n]) Returns a copy of s in which all (or the first n , if given) occurrences of the pattern have been replaced by a replacement string specified by repl , which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.

What is GSUB in regex?

gsub stands for global substitution (replace everywhere). It replaces every occurrence of a regular expression (original string) with the replacement string in the given string.

What is the difference between gsub () and sub ()?

The sub() and gsub() function in R is used for substitution as well as replacement operations. The sub() function will replace the first occurrence leaving the other as it is. On the other hand, the gsub() function will replace all the strings or values with the input strings.


1 Answers

String#gsub! modifies the original string, and returns that string or nil if no replacements were performed.

String#gsub does not modify the original string but always return the result even if nothing was changed.

Either return new_str at the end of your method, or use gsub instead of gsub!.

This is somewhat of a pattern in Ruby - when multiple version of a method exist, the one with ! will modify the receiver and the one without will simply return the result.

As an aside, it looks like you're not using the result of str.to_s for anything. If you know it's a string, to_s is pointless. If it might not be, you should make use of the result, for example like so:

str = str.to_s
like image 199
Jacob Raihle Avatar answered Oct 01 '22 01:10

Jacob Raihle