Or press ESC to close.

How to use Ruby to count characters in a string

14 Aug 2022 4 Min read
ruby logo

Ruby is an object-oriented programming language which focuses on productivity and simplicity. Ruby is called a “language of careful balance” and is used in various places like web development, web scraping, data processing, and task automation.

String (collection of characters) is treated as Object in Ruby that’s why Ruby provides many built-in and user defined methods to count number of characters in String.

In this article we will discuss all possible ways of counting characters using Ruby. Character counting is an important task in dictionaries, text processing applications, and in natural language processing applications. The following are some ways of counting characters in Ruby.

Count characters in Ruby using length method

This is the most basic way of counting characters in Ruby, length is a String class method in Ruby it returns count of number of characters in a string including white spaces, special characters, and other non-visible characters.

# Ruby Program for length method.


str = "Hello, world!"

puts str.length # prints 13 to the console

Count characters in Ruby using size method

This is another basic way of counting characters in Ruby, size is a String class method in Ruby which is alias to length method it returns count of number of characters in a string including white spaces, special characters, and other non-visible characters. There is no difference in size and length methods in terms of String class.

# Ruby Program for size method.

str = "Hello, world!"

puts str.size # prints 13 to the console

Count characters in Ruby using bytesize method

Ruby’s byte size is a String class method which counts number of bytes occupied by a String. The result is same as count of number of characters in String as each character occupies one byte in memory. White spaces are not ignored in bytesize method.

# Ruby Program for bytesize method.


str = "Hello, world!"

puts str.bytesize # prints 13 to the console

Count characters in Ruby using chars.count method

Ruby’s “chars” is a String class method which converts String into array of characters and then applying count method on that array gives number of characters in String. White spaces and special characters are not ignored in this method.

# Ruby Program for chars method.


str = "Hello, world!"

puts str.chars.count # prints 13 to the console

Count non-whitespace characters in Ruby using delete method

If you want to get character count without with-out white spaces, use Ruby’s delete method to remove all white spaces from String then use length method to get count of characters in String.

# Ruby Program for delete method.


str = "Hello, world!"

puts str.delete(" ").length # prints 12 to the console

Count non-whitespace characters in Ruby using gsub method

Ruby’s gsub method does global substitution on String and replaces space with “” empty character then using length method on resultant string returns total count of characters in string excluding white characters. The specialty of code below is that it excludes Unicode spaces as well.

# Ruby Program for gsub method.


str = " Hello, world! " # This string contains Unicode space.

puts str.gsub(/[[:space:, '').length # prints 12 to the console

Count characters without spaces at start or end in Ruby using strip method

If you want to get character count without white spaces at start or end of String, use Ruby’s strip method to remove all leading or trailing white spaces from String then use length method to get count of characters in String.

# Ruby Program for strip method.


# For leading white spaces

str_one = " Hello, world!"

puts str_one.strip.length # prints 13 to the console


# For trailing white spaces

str_two = "Hello, world! "

puts str_two.strip.length # prints 13 to the console

Count characters numeric or non-numeric using regexp

Regexp stands for Regular Expressions; regex is used to find specific patterns inside strings. Regexp has many applications like pattern matching or pattern recognition. In Ruby we can use regex to count characters in strings using various patterns, some examples are given below.

# Ruby Program for regexp method.


# For Numeric Character Counting Only

str_one = "Hello, world! 123"

regexp_one = Regexp.new(/\d+/)

puts str_one.match(regexp_one).to_s.size # prints 3 to the console


# For Digits and Alphabets Counting Only

str_two = "Hello, world! 1"

regexp_two = Regexp.new(/[a-zA-Z0-9_)

puts str_two.scan(regexp_two).length # prints 11 to the console


# For Alphabet Counting Only

str_three = "Hello, world! 1"

regexp_three = Regexp.new(/[[:alpha:)

puts str_three.scan(regexp_three).length # prints 10 to the console


# For Space Counting Only

str_four = "Hello, world! 1"

regexp_four = Regexp.new(/\s/)

puts str_four.scan(regexp_four).length # prints 2 to the console


# For Counting Characters except newline

str_five = "Hello, world! 1"

regexp_five = Regexp.new(/./)

puts str_five.scan(regexp_five).length # prints 15 to the console

Count characters using Proc

Proc Object is encapsulation of a block of code that can be stored in any variable. Proc is an essential concept of functional programming in Ruby and can be used for various purposes. Proc can be used to count number of characters in a String. Below is a code snippet for counting characters using Proc.

# Ruby Program for character counting using Proc.


char_counter = Proc.new {|x| x.size }

puts char_counter.call("Hello, world!") # prints 13 to the console

Count characters using Lambda

Lambda is also a kind of Proc except it has few execution differences as compared to Proc. Lambda can also be used to calculate count of characters in Ruby. Below is a code snippet for counting characters using Lambda.

# Ruby Program for character counting using Lambda.


char_counter_one = -> (x) { x.size }

# OR

char_counter_two = lambda { |x| x.size }

puts char_counter_one.call("Hello, world!") # prints 13 to the console

puts char_counter_two.call("Hello, world!") # prints 13 to the console

Count characters using loops

This approach for counting characters in string is very basic and traditional that’s why this approach will work in almost every platform. This method will count special characters and white characters as well.

# Ruby Program for character counting using for loop.


str = "Hello, world! 123"

count = 0

for i in Range.new(0, str.length - 1) do

   count += 1

end

puts count # prints 17 to the console

Another variant for “for loop” is as following:

# Ruby Program for character counting using for loop.


str = "Hello, world! 123"

count = 0

for i in str.chars do

   count += 1

end

puts count # prints 17 to the console

Same character counting can be done using until loop.

# Ruby Program for character counting using until loop.


str = "Hello, world!"

count = 0


until count == str.size do

   count += 1

end

puts count # prints 13 to the console

Now that you’ve read this post, you know about many ways of counting characters in Ruby. There are many other ways to count characters in Ruby as programming is a creative task and you can build many solutions for same problem. But stated above are most common ways of counting characters in Ruby.