Question

I'm having trouble understanding whats going on with this inject method. Its from a previous version of the octokit gem 1.25.0

VALID_OPTIONS_KEYS = [
      :adapter,
      :faraday_config_block,
      :api_version,
      :api_endpoint,
      :web_endpoint,
      :status_api_endpoint,
      :login,
      :password,
      :proxy,
      :oauth_token,
      :client_id,
      :client_secret].freeze

and here is the action

VALID_OPTIONS_KEYS.inject({}){|o,k| o.merge!(k => send(k)) }

can anyone help me out. I'm interested in the various ways this can be explained. Thanks

Was it helpful?

Solution

VALID_OPTIONS_KEYS holds all the symbolic method names. Now the line VALID_OPTIONS_KEYS.inject({}){|o,k| o.merge!(k => send(k)) } will create a Hash where key will be the name of the symbolic method and value will be the result of the symbolic method.

Very similar to below:

VALID_OPTIONS_KEYS = [
      :downcase,
      :upcase].freeze

VALID_OPTIONS_KEYS.inject({}){|o,k| o.merge!(k => "aa".send(k)) }
# => {:downcase=>"aa", :upcase=>"AA"}

The documentation Enumerable#inject is very clear to understand how inject works.

If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.

So we pass inject at the beginning an empty Hash o. Then inside the block with each pass the Hash object o, using the method Hash#merge,keep updating with new key/value pair. Where key is the method name from the array VALID_OPTIONS_KEYS, and the value is the result of the method call.

Hope it will help you!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top