Ruby - Count characters excluding whitespace

Introduction

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.

Demo

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

Result

Related Topic