Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Javaプログラマーが学ぶRuby基礎/属性の設定

概要

Rubyの属性の設定について説明します。

構文

Rubyの属性の設定は以下の構文で利用出来ます。

def sample; @sample; end
def sample=(sample);@sample=sample;end

また、仮想属性として外部からは通常の属性と同じように見せつつ
実際は別のフィールドに値を設定することも出来ます。

def another; @sample; end
def another=(another);@sample=another;end

サンプル

class Cart
  attr_accessor:quantity
  def quantity; @quantity ;end
  def quantity=(quantity) ; @quantity=quantity; end
  def dozen; @quantity/12; end # 仮想属性
  def dozen=(dozen); @quantity=dozen*12; end # 仮想属性
end

cart = Cart.new
cart.quantity = 16
puts "数量は#{cart.quantity}"
puts "数量は#{cart.dozen}ダース"
cart.dozen = 4
puts "数量は#{cart.quantity}"
puts "数量は#{cart.dozen}ダース"

出力

数量は16個
数量は1ダース
数量は48個
数量は4ダース