プログラミング基礎用語である「メッセージ」と「メソッド」の違いについて、書籍で説明している箇所を見つけたのでメモ。
プログラミングで、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が発生します。これは、次のように解釈できるでしょう。
bob
はメッセージを受け取ることができる。bob
はstand_up
というメッセージを受け取り、実行しようとする。すなわち、stand_up
という名前のデータにアクセスしようとする。stand_up
は見つからなかったので、NoMethodErrorを返す。擬人化するならば、このように言えるでしょうか。bob
君としては、「先輩!stand_up
しろっていわれたのでやろうとしましたが、自分はそのやり方を知らなかったみたいす!」。
以上をまとめると、メッセージとメソッドの違いについては、次のようにまとめることができます。
Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?
コメント