0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Ruby]tapメソッドでHashの初期化と同時にその階層を定義する

Last updated at Posted at 2020-11-01

参考書とかに書いてあるのだろうと思いますが、備忘録代わりに。

たとえば

以下のような複数の要素が混ざった配列を連想配列で分離させたい場合


array = [1, 2, "a", 3, "b", "c", 4]

ideal_hash = {
  hoge: [1, 2, 3, 4],
  fuga: ["a", "b", "c"]
}

今まで自分が書いていたコード


ideal_hash = { hoge: [], fuga: [] }

array.each do |i|
  i.is_a?(Integer) ? hash[:hoge] << i : hash[:fuga] << i
end

こうも書けるということを最近知った

tapメソッドは生成した自分自身を返すので、スッキリ書けるというのもあり、できるだけ使っていきたいという気持ちがあります。


ideal_hash = { hoge: [], fuga: [] }.tap do |hash|
  array.each do |i|
    i.is_a?(Integer) ? hash[:hoge] << i : hash[:fuga] << i
  end
end
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?