Help us understand the problem. What is going on with this article?

Ruby 配列展開 *Array

@koshi_life です。

*Array の記法が読めなかったので備忘です。

前提

  • ruby 2.6

読めなかったコード

hoge = {name: 'hoge', address: 'hoge@example.jp'}
a = [{name: 'a1', address: 'a1@example.jp'}]
b = [{name: 'b1', address: 'b1@example.jp'}, {name: 'b2', address: 'b2@example.jp'}]
c = [{name: 'c1', address: 'c1@example.jp'}, {name: 'c2', address: 'c2@example.jp'}, {name: 'c3', address: 'c3@example.jp'}]

addresses = [
  hoge[:address],
  *a.pluck(:address),
  *b.pluck(:address),
  *c.pluck(:address)
]

ちなみに pluckは

引数に指定したカラムの配列を返すメソッドです。このメソッドはRailsで使用できるメソッドなので、Rubyのみでは使用することができません。
mapとpluck より

> b.pluck(:address)
=> ["b1@example.jp", "b2@example.jp"]

pluck部分は上記リンク,consoleで試して読めたのでコードを簡略化します。

読めなかったのは *Array

hoge = {name:'hoge', address:'hoge@jp'}
a = ['a1@jp']
b = ['b1@jp', 'b2@jp']
c = ['c1@jp', 'c2@jp', 'c3@jp']

addresses = [
  hoge[:address],
  *a,
  *b,
  *c
]
=> ["hoge@jp", "a1@jp", "b1@jp", "b2@jp", "c1@jp", "c2@jp", "c3@jp"]

*をつけないと

addresses = [
  hoge[:address],
  a,
  b,
  c
]
=> ["hoge@jp", ["a1@jp"], ["b1@jp", "b2@jp"], ["c1@jp", "c2@jp", "c3@jp"]]

結論

*Array は配列の要素を展開してくれる便利な記法。

# ちなみに以下と同意
> [hoge[:address]] + a + b + c
=> ["hoge@jp", "a1@jp", "b1@jp", "b2@jp", "c1@jp", "c2@jp", "c3@jp"]

参考

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away