IT박스

개수, 크기, 길이… 루비에서 너무 많은 선택이 있습니까?

itboxs 2020. 6. 22. 08:08
반응형

개수, 크기, 길이… 루비에서 너무 많은 선택이 있습니까?


나는 이것에 대한 결정적인 대답을 찾을 수없는 것 같아서 이것을 "n 번째 수준"으로 이해하고 싶습니다 :-)


    a = { "a"=> "Hello", "b"=> "World"}
    a. 카운트 # 2
    a. 크기 # 2
    길이 # 2

    a = [10, 20]
    a. 카운트 # 2
    a. 크기 # 2
    길이 # 2

그래서 어느 것을 사용해야합니까? 하나 이상의 요소가 있는지 알고 싶다면 중요하지 않지만 실제 차이점을 이해하고 싶습니다. 이것은 배열에도 적용됩니다. 나는 같은 결과를 얻습니다.

또한 ActiveRecord와 개수 / 크기 / 길이가 다른 의미를 가지고 있음을 알고 있습니다. 나는 대부분 순수한 루비 (1.92)에 관심이 있지만, AR의 차이에 대해 누군가가 알고 싶다면 그 점을 높이 평가할 것이다.

감사!


배열과 해시 size의 별칭은 length입니다. 그것들은 동의어이며 정확히 같은 일을합니다.

count 보다 다재다능합니다. 요소 또는 술어를 가져와 일치하는 항목 만 계산할 수 있습니다.

> [1,2,3].count{|x| x > 2 }
=> 1

계산할 매개 변수를 제공 하지 않는 경우 기본적으로 호출 길이와 동일한 효과가 있습니다. 그러나 성능 차이가있을 수 있습니다.

Array소스 코드에서 거의 똑같은 일을 볼 수 있습니다. 다음은 구현을위한 C 코드입니다 array.length.

static VALUE
rb_ary_length(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    return LONG2NUM(len);
}

그리고 여기 구현의 관련 부분이 있습니다 array.count.

static VALUE
rb_ary_count(int argc, VALUE *argv, VALUE ary)
{
    long n = 0;

    if (argc == 0) {
        VALUE *p, *pend;

        if (!rb_block_given_p())
            return LONG2NUM(RARRAY_LEN(ary));

        // etc..
    }
}

에 대한 코드 array.count는 몇 가지 추가 검사를 수행하지만 결국 정확히 동일한 코드를 호출합니다 LONG2NUM(RARRAY_LEN(ary)).

반면 해시 ( 소스 코드 )는 자체 최적화 된 버전을 구현하지 않는 count것이므로 Enumerable( 소스 코드 ) 의 구현 이 사용됩니다.이 소스 코드 는 모든 요소를 ​​반복하고 하나씩 계산합니다.

일반적으로 얼마나 많은 요소가 있는지 알고 싶다면 대신 length(또는 별명 size)을 사용하는 것이 좋습니다 count.


액티브와 관련, 다른 한편으로는, 거기에 있는 중요한 차이점은. 이 게시물을 확인하십시오 :


데이터베이스 연결을 사용하는 응용 프로그램에는 중요한 차이점이 있습니다.

많은 ORM (ActiveRecord, DataMapper 등)을 사용하는 경우 일반적인 이해는 .size가 데이터베이스에서 모든 항목을 요청하는 쿼리 ( 'select * from mytable')를 생성 한 다음 항목 수를 제공한다는 것입니다. 결과적으로 .count는 훨씬 빠른 단일 쿼리 ( 'select count (*) from mytable')를 생성합니다.

이러한 ORM은 가장 놀랍게도 원칙을 따르기 때문에 널리 퍼지기 때문입니다. 일반적으로 메모리에 이미 무언가가 있으면 .size를 사용하고 코드에서 데이터베이스 (또는 API를 통한 외부 서비스)에 대한 요청을 생성하면 .count를 사용합니다.


대부분의 경우 (예 : Array 또는 String ) size는의 별칭 입니다 length.

count normally comes from Enumerable and can take an optional predicate block. Thus enumerable.count {cond} is [roughly] (enumerable.select {cond}).length -- it can of course bypass the intermediate structure as it just needs the count of matching predicates.

Note: I am not sure if count forces an evaluation of the enumeration if the block is not specified or if it short-circuits to the length if possible.

Edit (and thanks to Mark's answer!): count without a block (at least for Arrays) does not force an evaluation. I suppose without formal behavior it's "open" for other implementations, if forcing an evaluation without a predicate ever even really makes sense anyway.


I found a good answare at http://blog.hasmanythrough.com/2008/2/27/count-length-size

In ActiveRecord, there are several ways to find out how many records are in an association, and there are some subtle differences in how they work.

post.comments.count - Determine the number of elements with an SQL COUNT query. You can also specify conditions to count only a subset of the associated elements (e.g. :conditions => {:author_name => "josh"}). If you set up a counter cache on the association, #count will return that cached value instead of executing a new query.

post.comments.length - This always loads the contents of the association into memory, then returns the number of elements loaded. Note that this won't force an update if the association had been previously loaded and then new comments were created through another way (e.g. Comment.create(...) instead of post.comments.create(...)).

post.comments.size - This works as a combination of the two previous options. If the collection has already been loaded, it will return its length just like calling #length. If it hasn't been loaded yet, it's like calling #count.

Also I have a personal experience:

<%= h(params.size.to_s) %> # works_like_that !
<%= h(params.count.to_s) %> # does_not_work_like_that !

We have a several ways to find out how many elements in an array like .length, .count and .size. However, It's better to use array.size rather than array.count. Because .size is better in performance.


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.

참고URL : https://stackoverflow.com/questions/4550770/count-size-length-too-many-choices-in-ruby

반응형