LoginSignup
12
1

More than 1 year has passed since last update.

Rails6 のちょい足しな新機能を試す8(index_with 編)

Last updated at Posted at 2019-04-26

はじめに

Rails 6 に追加されそうな新機能を試す第8段。 今回のちょい足し機能は、 index_with 編です。
配列などの各要素をキーとするHashを生成します。 index_by の逆バージョンみたいなメソッドです。
Rubyの標準ライブラリ Enumerable にちょい足しされます。

記載時点では、Rails は 6.0.0.rc1 です。 gem install rails --prerelease でインストールできます。

$  rails --version
Rails 6.0.0.rc1

irb を実行する

rails プロジェクトを作らなくても試せるので、試してみましょう。

$ irb -ractive_support/core_ext

Enumerable#index_with{...}

ブロックを指定して呼び出すと、各要素をキーとして、ブロックを評価した結果を値とするHashを生成します。

irb(main):001:0> %w[a b].index_with{|e| e.upcase}
=> {"a"=>"A,", "b"=>"B"}

Enumerable#index_with(xxx)

引数を指定して呼び出すと、引数を値とするHashを生成します。

irb(main):002:0> %w[a b].index_with('')
=> {"a"=>"", "b"=>""}

ブロックと引数を同時に指定したら?

ブロックと引数を同時に指定するとブロックが優先されます。

irb(main):003:0> %w[a b].index_with(''){|e| e.upcase}
=> {"a"=>"A", "b"=>"B"}

index_by との比較

index_withindex_by を比較してみると

  • index_with は各要素をキーとしてブロックの評価結果(または引数)を値とするHashを作る。
  • index_by はブロックの評価結果をキーとして各要素を値とするHashを作る。

と逆バージョンのような関係にあります。

irb(main):004:0> %w[a b].index_with{|e| e.upcase}
=> {"a"=>"A", "b"=>"B"}
irb(main):005:0> %w[a b].index_by{|e| e.upcase}
=> {"A"=>"a", "B"=>"b"}

参考情報

12
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
1