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?

【Rails】Railsのスプラット演算子 * を理解する

Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。
Railsのコードを読んでいると、permit(*base_params)pluck(*columns) のように * が使われていることがあります。
これは「スプラット演算子」と呼ばれるRubyの機能で、TypeScript/JavaScriptの ... (スプレッド構文)にとてもよく似ています。
本記事では、Railsでのスプラット演算子の使い方を整理し、TS/JSとの違いもあわせて解説します。


1. Rubyのスプラット演算子とは?

Rubyにおける * の役割は大きく2つ。

  1. 配列を展開して引数に渡す
def sum(a, b, c)
  a + b + c
end

nums = [1, 2, 3]
sum(*nums) # => 6
# sum(1, 2, 3) と同じ意味
  1. 可変長引数を受け取る
def sum(*nums)
  nums.sum
end

sum(1, 2, 3, 4) # => 10

2. Railsでの利用例

(1) Strong Parameters

def create_params
  params.require(:student).permit(:name, :grade, *base_params)
end
  • 共通パラメータを配列でまとめておき、* で展開して渡せる

(2) ActiveRecord

Student.pluck(*%i[name email grade])
# => ["Taro", "taro@example.com", 3]

3. TypeScript/JavaScriptのスプレッド構文との比較

両者はほぼ同じ発想で使われています。

機能 Ruby TS/JS
配列展開 sum(*nums) sum(...nums)
可変長引数 def foo(*args) function foo(...args)
オブジェクト展開 **hash { ...object }

例(オブジェクト展開):

Ruby:

base = { name: "Taro", age: 20 }
user = { **base, grade: "A" }
# => {:name=>"Taro", :age=>20, :grade=>"A"}

TypeScript:

const base = { name: "Taro", age: 20 };
const user = { ...base, grade: "A" };
// { name: "Taro", age: 20, grade: "A" }

4. 注意点

  • *nil はエラーになるので Array(base_params) としておくと安全
  • 可読性が下がるケースもあるので、シンプルさを優先する

まとめ

  • Railsの * は「配列を展開する」「可変長引数を受け取る」というRubyの基本機能
  • TypeScript/JavaScriptの ... と非常に似ており、違いはオブジェクト展開で ** を使う点
  • Strong Parameters や ActiveRecord のメソッドで頻出するので、仕組みを理解しておくとコードが読みやすくなる
0
0
1

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?