DEV Community

Brian Waddell
Brian Waddell

Posted on

TIL #4

Hello I am continuing the learn a lot of tricks and really cool methods in Ruby. Today I learned more about the advance gsub techniques which ruby has to offer. gsub is a technique in Ruby programming that takes all the occurrences of the first argument and replaces that with what is written the second argument in the original string. You can also use this method to remove everything except for digits, words, and whitespaces. You can also call on the count method to then count what is left over depending on what you removed and what is left within the original string. This has proven to be helpful when trying to count how many letters a string has when the original contained letters and numbers and we only want to consider the letters or the numbers within the String.

Below is an example of code that removes everything except letters and then the count method is evoked to return a count of what has been left over in this case the letters.

pp"Number of letters in the string is: " +string.gsub(/[^a-z]/i, "").count(string).to_s

Top comments (0)