2021-05-09に更新

「メソッド」と「メッセージ」はどう違うのか

要約

プログラミング基礎用語である「メッセージ」と「メソッド」の違いについて、書籍で説明している箇所を見つけたのでメモ。

「メソッド」と「メッセージ」

プログラミングで、foo.bar.barのことを、オブジェクトに対する「メソッド」と呼でいる文章と「メッセージ」と呼んでいる文章の2種類をときどき見かけます。どうして用語法が違うのだろう?

なぜ用語を二つに分けるのか

Why bother saying both “sending the message ‘to_i’” and “calling the method to_i”? Why have two ways of describing the same operation? Because they aren’t quite the same. Most of the time, you send a message to a receiving object, and the object executes the corresponding method. But sometimes, there is no corresponding method. You can put anything to the right of the dot, and there’s no guarantee that the receiver will have a method that matches the message you send.

The Well-Grounded Rubyist, Chapter 1.1.4 Method calls, messages, and Ruby objects

「メソッド」と「メッセージ」は厳密には同じではない

詳しくみます。

Why bother saying both “sending the message ‘to_i’” and “calling the method to_i”? Why have two ways of describing the same operation? Because they aren’t quite the same.

なぜに「メッセージを送る」とか「メソッドを呼ぶ」とか別の言い方、表現をするのか?それは、厳密にはその二つが同じじゃないからである。と言っています。

Most of the time, you send a message to a receiving object, and the object executes the corresponding method. But sometimes, there is no corresponding method. You can put anything to the right of the dot, and there’s no guarantee that the receiver will have a method that matches the message you send.

多くの場合、受信する側のオブジェクトに「メッセージ」を送ることで、そのメッセージを受信したオブジェクトが、対応するメソッドを実行する。

が、メッセージには(原理的に)なんでも書いていいので、受け取ったメッセージに対応するメソッドが存在しないという場合がある。

メソッドが存在するか否か

以下の例を考えます。

# Person.rb

class Person

  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello! My name is #{@name}."
  end
end

bob = Person.new("Bob")

bob.greet # "Hello! My name is Bob."

この例の最後の行では、オブジェクトbobはメッセージgreetを受け取り、「了解っす!対応するメソッドを実行しまっす!」といって、自身に定義されているgreetメソッドをきちんと実行できました。

ここで、このbobくんにstand_upというメッセージを送ったとします。

# Person.rb

class Person

  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello! My name is #{@name}."
  end
end

bob = Person.new("Bob")

bob.stand_up # NoMethodError

bob.stand_upを実行しようとすると、NoMethodErrorが発生します。これは、次のように解釈できるでしょう。

  1. オブジェクト(インスタンス)として生成されたbobメッセージを受け取ることができる。
  2. bobstand_upというメッセージを受け取り、実行しようとする。すなわち、stand_upという名前のデータにアクセスしようとする。
  3. 自分のアクセスできるデータのなかにstand_upは見つからなかったので、NoMethodErrorを返す。

擬人化するならば、このように言えるでしょうか。bob君としては、「先輩!stand_upしろっていわれたのでやろうとしましたが、自分はそのやり方を知らなかったみたいす!」。

以上をまとめると、メッセージとメソッドの違いについては、次のようにまとめることができます。

  • メッセージ:オブジェクトに対する指示。対象のオブジェクトが、その指示を実行できるかどうかはわからない。
  • メソッド:オブジェクトが持っている関数。
ツイッターでシェア
みんなに共有、忘れないようにメモ

mkataoka73

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント