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

前端 未结 6 463
逝去的感伤
逝去的感伤 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:55

    In most cases (e.g. Array or String) size is an alias for 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.

提交回复
热议问题