module Enumerable
def index_with(default = (no_default = true))
%i( created_at updated_at ).index_with(Time.now)
for all elements:
If an argument is passed instead of a block, it will be used as the value
# => { title: "hey there", body: "what's up?" }
%i( title body ).index_with { |attr_name| post.public_send(attr_name) }
post = Post.new(title: "hey there", body: "what's up?")
result as the value.
Convert an enumerable to a hash, using the element as the key and the block
def index_with(default = (no_default = true)) if block_given? result = {} each { |elem| result[elem] = yield(elem) } result elsif no_default to_enum(:index_with) { size if respond_to?(:size) } else result = {} each { |elem| result[elem] = default } result end end