LoginSignup
1
0

More than 3 years have passed since last update.

sendメソッドを調べてみた

Last updated at Posted at 2021-04-10

はじめに

railsで複数のカラムに、ある処理をして出力された値を入れたい場面で、sendメソッドが使用されていたので調べてました。

sendメソッドとは

レシーバが持っているメソッドをして、呼び出すメソッド

構文

send(name, *args)

name: メソッド名(文字列かシンボルで指定)
args: メソッドに渡す引数

使用場面

条件別にメソッドを呼び出したい、カラムに値を入れたい時に使用する

サンプルコード

class Exam
  def japanese(score)
    puts "国語は#{score}点です"
  end
  def math(score)
    puts "数学は#{score}点です"
  end
  def english(score)
    puts "英語は#{score}点です"
  end
end

exam = Exam.new
exam.send("japanese", 74) # => 国語は74点です
exam.send(:math, 69) # => 数学は69点です
exam.send(:english, 58) # => 英語は58点です

*カラムに値を入れる場合、
send("カラム名=", 入れたい値)
=を忘れないよう注意する必要がある。

# テーブル作成してある程で。
exam = Exam.new
exam.send("japanese=", 74) 

exam.japanese
=> 74

おわりに

'はじめに'で話した使用場面では、
name: 複数カラムを配列に格納
args: あるメソッド通って出力された値
に当てはめ、each文を使用して、3行で該当するカラム全てに値を入れ直すことが出来ていたので便利に感じた。

参考記事

1
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
1
0