ruby クラス

rubyのクラスについてメモ

① 初期化

変数名 = クラス名.new([引数1, 引数2, ・・・])
例:
class Human()
end

human = Human.new()

② initialize

クラス作成時に実行される特別なインスタンスメソッド
例:
class Human
    def initialize(humanName="noname")
        @name = humanname
    end
end

③ アクセスメソッド

attr_reader, attr_writer, attr_accessorなど
例:
class Human
    def initialize(humanName="noname", humanHeight=165, humanWeight=50)
        @name = humanName
        @height = humanHeight
        @weight = humanWeight
    end

    attr_reader :name      # 参照のみ可能
    attr_writer :height    # 書き込みのみ可能
    attr_accessor :weight  # 参照、書き込み可能
end

# クラスの初期化
mHALr = Human.new("mHALr", 999, 100)

# name
print(mHALr.name)    # 参照

# height
mHALr.height = 500   # 書き込み

# weight
mHALr.weight = 200   # 書き込み
print(mHALr.weight)  # 参照


スポンサーリンク
レクタングル広告(大)
レクタングル広告(大)

シェアする

  • このエントリーをはてなブックマークに追加

フォローする