Rails ActionController::Parameters each_pair and each_value returns an enumerator.

Rails has added changes to ActionController::Parameters #each_pair and #each_value methods to make sure they do not raise an error when called without a block. They will now return an enumerator when no block is given.

The change has been introduced to make sure these methods match the Hash’s behaviour.

# Hash#each_pair
{}.each_pair
=> #<Enumerator: {}:each_pair>

# Hash#each_value
=> #<Enumerator: {}:each_value>

Before the change

> params = ActionController::Parameters.new(search_query: 'books')
=> <ActionController::Parameters {"search_query"=>"books"} permitted: false>

# Call each_pair
> params.each_pair

LocalJumpError: no block given (yield)
from /lib/action_controller/metal/strong_parameters.rb:356:in `block in each_pair`

# Call each_value
> params.each_value

LocalJumpError: no block given (yield)
from /lib/action_controller/metal/strong_parameters.rb:367:in `block in each_value`

After the change

> params = ActionController::Parameters.new(search_query: 'books')
=> <ActionController::Parameters {"search_query"=>"books"} permitted: false>

# Call each_pair
> params.each_pair
=> #<Enumerator: <ActionController::Parameters {"search_query"=>"books"} permitted: false>:each_pair>

# Call each_value
> params.each_value
=> #<Enumerator: <ActionController::Parameters {"search_query"=>"books"} permitted: false>:each_value>

Internally, the methods will just call to_enum with method name when no block is given.

Summary

For ActionController::Parameters, this change places the methods each_pair and each_values in conjunction with other hashlike methods for the class which have similar behaviour when called without a block. For instance, ActionController::Parameters#transform_keys

Note

This change has been added recently and is expected to be released with Rails 6.1.

Need help on your Ruby on Rails or React project?

Join Our Newsletter