Indirect Variable Access
インスタンス変数の値を取り出したり設定したりするためのアクセサを用意しましょう。
インスタンス変数に関するパターンです。
Rubyだとattr_accessorを使うことで、簡単に間接アクセスを実現出来ます。
class Point attr_accessor :x, :y def initialize(x, y) @x = x @y = y end def display puts "x=#{x}, y=#{y}" end end point = Point.new(10, 5) point.x # => 10 point.x = 5 # => 5 point.display # >> 5,5
このように、インスタンス変数へのアクセスを間接的にしておくことで、プログラムを柔軟に拡張出来るようになります。
class PolarPoint < Point attr_accessor :r, :theta def initialize(r, theta) @r = r @theta = theta end def x r * Math.cos(theta) end def y r * Math.sin(theta) end end polar = PolarPoint.new(10, 45) polar.x # => 5.2532198881773 polar.y # => 8.50903524534118 polar.display # >> 5.2532198881773, 8.50903524534118