Home » Ruby programming » Ruby programs

Ruby program to count the number of words in a string

Counting the numbers of words in a String in Ruby: Here, we are going to learn how to count the total number of words in a given string in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 07, 2019

Counting words in a string

Given a string and we have to count the total number of words of the string in Ruby.

Ruby provides you several ways to count the number of words in a string. One of the ways can be implemented which requires converting the string into array by using .split method and the proceeding with count the array elements. But let us not get into complex things; the following code will let you know the easiest possible way to handle the situation.

Methods used:

  • puts: The most common method in every Ruby program. It is used to convey some message to the user.
  • gets: It is used for taking input from the user.
  • .length: This method returns the length of the string.

Variables used:

  • str1: This is holding the string entered by the user.
  • count: It is acting as a counter which is counting the number of words in the string.

Ruby code to count the number of words in the string

Ruby program to find number of words in a string.

puts "Enter the String:"

for i in 1..str1.length
	if (str1[i] == ' ')

puts "Number of words are #{count}"


RUN 1:
Enter the String:
hello guys! You are at Includehelp
Number of words are 6

RUN 2:
Enter the String:
Destiny is powerful!
Number of words are 3

Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.