It will be a memo for learning. In ruby, use the length method or size method to get the number of elements in the array.
Also, it is convenient to use the count method to specify the conditions and retrieve the elements of the array.
In this article, you will learn the basic usage.
If you want to know the number of elements in an array, use the "length method" or "size method", but there are two types of length, the array class and the string class.
The length method of the array class is used for arrays and returns the number of elements in the array.
Also, the length method of the strign class returns the number of characters when used on a variable that contains a string.
array = ["red","blue","yellow"]
str = "Engineers"
p array.length
p str.length
[Execution result]
3
6
The size method returns exactly the same result as the length method.
array = ["red","blue","yellow"]
str = "Engineers"
p array.size
p str.size
[Execution result]
3
6
If you want to conditionally count the elements of an array, use the count method.
By specifying a condition in the argument, you can get only the number of elements that meet the condition.
If you want to know the number of elements of “red”
array = ["red","blue","yellow","red","green"]
p array.count("red")
[Execution result]
2
You can also specify a slightly more complicated condition by passing a block as an argument.
Let's count the number of elements whose remainder is 0, that is, the number of even numbers.
array = [1,2,2,2,3,3,4,5,]
p array.count{ |num| num % 2 == 0}
[Execution result]
4
Also, if you use the count method without specifying an argument, the number of elements is returned in the same way as length and size.
I don't want to count nil if the array contains nil! In that case, specify the condition in the count method.
array = ["red","blue",nil,"yellow"]
p array.count{ |num| !num.nil? }
[Execution result]
3
This time I learned how to use the length, size and count methods. I would appreciate it if you could point out any mistakes.
Recommended Posts