Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count ALL Characters in a String in Ruby

Tags:

string

ruby

count

Is there an equivalent to PHP's strlen method in Ruby?

I know about Ruby's String#count method, but it requires that I define a set of characters to count. In my situation, I want to count ALL characters, not just certain characters.

like image 573
filmnut Avatar asked May 28 '14 20:05

filmnut


People also ask

How do you use count in Ruby?

Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.

How do I use GSUB in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

What does split do in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

How do you find the occurrence of a character in a string?

In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.


1 Answers

Use String#size or String#length method. It will work for you.

Returns the character length of str.

Example :

"abc 12-".size  # => 7
like image 119
Arup Rakshit Avatar answered Oct 03 '22 08:10

Arup Rakshit