instance method
index_with
Ruby on Rails 6.0.6
Since v6.0.6Signature
index_with(default = INDEX_WITH_DEFAULT)
Convert an enumerable to a hash keying it with the enumerable items and with the values returned in the block.
post = Post.new(title: "hey there", body: "what's up?") %i( title body ).index_with { |attr_name| post.public_send(attr_name) } # => { title: "hey there", body: "what's up?" }
Parameters
-
defaultopt = INDEX_WITH_DEFAULT
Source
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 70
def index_with(default = INDEX_WITH_DEFAULT)
if block_given?
result = {}
each { |elem| result[elem] = yield(elem) }
result
elsif default != INDEX_WITH_DEFAULT
result = {}
each { |elem| result[elem] = default }
result
else
to_enum(:index_with) { size if respond_to?(:size) }
end
end
Defined in activesupport/lib/active_support/core_ext/enumerable.rb line 70
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Enumerable