1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Clarify index_by and index_with docs [ci skip]

Make it clearer how the key and value are derived in both cases, and use
the same sentence structure so that it's easier understand one method in
terms of the other.

Also add an example of passing a default value to `index_with`.
This commit is contained in:
Eugene Kenny 2020-03-07 22:03:26 +00:00
parent ec69083cf3
commit 94b7453089

View file

@ -44,7 +44,8 @@ module Enumerable
end end
end end
# Convert an enumerable to a hash keying it by the block return value. # Convert an enumerable to a hash, using the block result as the key and the
# element as the value.
# #
# people.index_by(&:login) # people.index_by(&:login)
# # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...} # # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
@ -61,12 +62,19 @@ module Enumerable
end end
end end
# Convert an enumerable to a hash keying it with the enumerable items and with the values returned in the block. # Convert an enumerable to a hash, using the element as the key and the block
# result as the value.
# #
# post = Post.new(title: "hey there", body: "what's up?") # post = Post.new(title: "hey there", body: "what's up?")
# #
# %i( title body ).index_with { |attr_name| post.public_send(attr_name) } # %i( title body ).index_with { |attr_name| post.public_send(attr_name) }
# # => { title: "hey there", body: "what's up?" } # # => { title: "hey there", body: "what's up?" }
#
# If an argument is passed instead of a block, it will be used as the value
# for all elements:
#
# %i( created_at updated_at ).index_with(Time.now)
# # => { created_at: 2020-03-09 22:31:47, updated_at: 2020-03-09 22:31:47 }
def index_with(default = INDEX_WITH_DEFAULT) def index_with(default = INDEX_WITH_DEFAULT)
if block_given? if block_given?
result = {} result = {}