14
7

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 5 years have passed since last update.

Ruby 配列展開 *Array

Last updated at Posted at 2019-03-24

@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"]

参考

14
7
2

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
14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?