Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
7
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Organization

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 not register and get more from Qiita?
  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
7
Help us understand the problem. What are the problem?