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】引数の記法

Posted at

はじめに

引数の記法についての学習記録です。

よく使う引数

記法 説明 使用例
def method(a, b) 位置引数 method(1, 2)
def method(a = 1) デフォルト引数 method() / method(5)
def method(*args) 可変長位置引数 method(1, 2, 3)
def method(a:, b:) キーワード引数(必須) method(a: 1, b: 2)
def method(a: 1, b: 2) キーワード引数(デフォルトあり) method() / method(b: 5)
def method(**kwargs) 任意のキーワード引数 method(foo: "bar", baz: 123)
def method(_, name) 無視する引数 method("不要", "太郎")

_ (アンダースコア)

  • _ アンダースコアはRubyでは「無視する値」を表す慣習的な記法
  • 構文上必要な場合や意図的に無視する場合に使う
def greet(_, name)
  puts "Hello, #{name}."
end

greet("Taro", "Hanako") # Hello, Hanako. 

* (アスタリスク)

*args は可変長引数を受け取る

  • 複数の引数を配列として受け取る
  • 引数がなくてもエラーにならない
def show_args(*args)
  puts "位置引数: #{args}"
end

show_args(1,2,3)  # 位置引数: [1, 2, 3]
show_args() # 位置引数: []
show_args # 位置引数: []

**kwargs はキーワード引数を受け取る

  • 複数のキーワード引数をまとめて受け取り、ハッシュとして扱うための記法
  • 引数がなくてもエラーにならない
def show_kwargs(**kwargs)
 puts "キーワード引数: #{kwargs}"
end

show_kwargs(type: 'child', fee: 1000) # キーワード引数: {:type=>"child", :fee=>1000}
show_kwargs() # キーワード引数: {}
show_kwargs # キーワード引数: {}

順序のポイント

  • キーワード引数は呼び出し時には順番を気にしなくて良い
  • **kwargsは最後に置く。ただし、&block(ブロック引数) を使う場合は、**kwargs の後に置く
def method_name(
  required_arg,         # 通常の必須引数
  default_arg = "default",  # デフォルト引数
  *args,                # 可変長引数(位置引数)
  keyword_arg:,         # 必須キーワード引数
  keyword_default: "x", # デフォルト付きキーワード引数
  **kwargs              # 任意キーワード引数(ハッシュ)
)
end
def example(a, b = 1, *rest, x:, y: "default", **kwargs, &block)
  puts "a: #{a}, b: #{b}, rest: #{rest}, x: #{x}, y: #{y}, kwargs: #{kwargs}"
  block.call if block
end

example(10, 20, 30, x: "X", debug: true) { puts "ブロック" }
# a: 10, b: 20, rest: [30], x: X, y: default, kwargs: {:debug=>true}
# ブロック

その他

&block (ブロック引数)

  • ブロックを引数として受け取る
  • block.callでブロックを実行する
def greet(&block)
  puts "Hello."
  block.call if block
end

greet { puts "私はブロックです。" }

# Hello.
# 私はブロックです。
def greet_with_name(name, &block)
  block.call(name)
end

greet_with_name("太郎") { |n| puts "Hello. 私は#{n}です。" }  # Hello. 私は太郎です。

Procオブジェクト

  • ブロックをオブジェクトして扱う
def call_proc(proc_obj) # proc_objは引数として受け取ったProcオブジェクト
  proc_obj.call("Hanako")
end

greeting = Proc.new { |name| puts "こんにちは、#{name}さん!" }
call_proc(greeting) # こんにちは、Hanakoさん!

lambda

  • 引数の数がProcよりも厳密(lambdaは引数の数が一致しないとエラーになるが、Procは足りない引数をnilにして処理を続ける)
def call_lambda(lam)
  lam.call("Hanako")
end

greeting = ->(name) { puts "こんにちは、#{name}さん!" }
call_lambda(greeting) # こんにちは、Hanakoさん! 
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?