Ruby - Count characters excluding whitespace


strings have a gsub method that performs a global substitution upon the string. For example:

"this is a test".gsub(/t/, 'X')  # Xhis is a XesX 

You can use gsub to eradicate the spaces from your text string.

Then use the length method to get the length of the text.


lines = File.readlines("main.rb") 
line_count = lines.size #   w  ww. j ava 2 s  . c om
text = lines.join 
total_characters_nospaces = text.gsub(/\s+/, '').length 
puts "#{total_characters_nospaces} characters excluding spaces"


Related Topic