module Enumerable
def index_with(default = INDEX_WITH_DEFAULT)
%i( title body ).index_with { |attr_name| post.public_send(attr_name) }
post = Post.new(title: "hey there", body: "what's up?")
Convert an enumerable to a hash keying it with the enumerable items and with the values returned in the block.
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