How is each_with_object supposed to work?

后端 未结 3 1894
鱼传尺愫
鱼传尺愫 2020-12-09 15:00

I\'m trying to figure out how each_with_object is supposed to be used.

I have a sum example that doesn\'t work:

> (1..3).each_with_ob         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-09 15:40

    A simple, but common example using each_with_object is when you need to build a hash depending on elements in an array. Very often you see something like:

    hash = {}
    [1, 2, 3, 4].each { |number| hash[number] = number**2 }
    hash
    

    Using each_with_object avoids the explicit initialization and return of the hash variable.

    [1,2,3,4].each_with_object({}) { |number, hash| hash[number] = number**2 }
    

    I advise reading the docs for inject, tap and each_with_index. These methods are helpful when you aim for short and readable code.

提交回复
热议问题