instance method index_with

Ruby on Rails 6.0.6

Since v6.0.6

Available in: v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

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

default opt = 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

Type at least 2 characters to search.

↑↓ navigate · open · esc close