What is the difference between "keys.each" and "each_key"?

When repeating through a hash, as shown below:

hash.keys.each do |key| process_key(key) end 

To declare Rubocop I should use:

 each_key 

instead:

 keys.each 

What is the “key” difference between keys.each and each_key ?

+5
source share
2 answers

Rubocop is wrong. Which one should be used depends on what you want as the return value.

  • If you want to return an array of keys, you must use keys.each . key creates a new array of keys, and each returns this array of keys after executing a block on each key.
  • If you do not need to have an array of keys (and want to return the original hash), you should use each_key , as this does not create an array that will not be used, and will be more efficient.
+2
source

Rubocop wants you to keep track of this based on your rated code due to performance. The use of large data sets where it becomes noticeable. Here's the document on it: https://github.com/bbatsov/rubocop/blob/master/manual/cops_performance.md#performancehasheachmethods

I also found a benchmark that someone wrote to check this: https://gist.github.com/jodosha/8ca2bee6137be94e9dcb

I modified it a bit and enabled it on my systems:

 Warming up -------------------------------------- string each 128.742ki/100ms string keys 114.523ki/100ms string each_key 134.279ki/100ms symbol each 128.838ki/100ms symbol keys 109.398ki/100ms symbol each_key 132.021ki/100ms Calculating ------------------------------------- string each 2.053M (± 4.0%) i/s - 10.299M in 5.026890s string keys 1.864M (± 1.4%) i/s - 9.391M in 5.039759s string each_key 2.224M (± 5.5%) i/s - 11.145M in 5.032201s symbol each 2.082M (± 1.0%) i/s - 10.436M in 5.013145s symbol keys 1.815M (± 2.1%) i/s - 9.080M in 5.004690s symbol each_key 2.240M (± 1.9%) i/s - 11.222M in 5.012184s Comparison: symbol each_key: 2239720.0 i/s string each_key: 2224205.1 i/s - same-ish: difference falls within error symbol each: 2081895.2 i/s - 1.08x slower string each: 2052884.9 i/s - 1.09x slower string keys: 1863740.5 i/s - 1.20x slower symbol keys: 1815131.1 i/s - 1.23x slower 

Method chains will be slower than using the built-in method (in this case), which performs the task using one special enumerator. The creators of the language put it there for some reason, as well as its idiom.

+4
source

Source: https://habr.com/ru/post/1272289/


All Articles