Count, size, length…too many choices in Ruby?

前端 未结 6 455
逝去的感伤
逝去的感伤 2021-01-29 20:18

I can\'t seem to find a definitive answer on this and I want to make sure I understand this to the \"n\'th level\" :-)


    a = { \"a\" => \"Hello\", \"b\" => \"Worl         


        
6条回答
  •  后悔当初
    2021-01-29 20:57

    Adding more to Mark Byers answer. In Ruby the method array.size is an alias to Array#length method. There is no technical difference in using any of these two methods. Possibly you won't see any difference in performance as well. However, the array.count also does the same job but with some extra functionalities Array#count

    It can be used to get total no of elements based on some condition. Count can be called in three ways:

    Array#count # Returns number of elements in Array

    Array#count n # Returns number of elements having value n in Array

    Array#count{|i| i.even?} Returns count based on condition invoked on each element array

    array = [1,2,3,4,5,6,7,4,3,2,4,5,6,7,1,2,4]
    
    array.size     # => 17
    array.length   # => 17
    array.count    # => 17
    

    Here all three methods do the same job. However here is where the count gets interesting.

    Let us say, I want to find how many array elements does the array contains with value 2

    array.count 2    # => 3
    

    The array has a total of three elements with value as 2.

    Now, I want to find all the array elements greater than 4

    array.count{|i| i > 4}   # =>6
    

    The array has total 6 elements which are > than 4.

    I hope it gives some info about count method.

提交回复
热议问题