LoginSignup
0
0

More than 5 years have passed since last update.

ruby oop

Last updated at Posted at 2016-08-04

rubyのオブジェクト指向について自分なりの解釈でまとめてみた。

Ruby OOP

Object Oriented Programming

対象(オブジェクト)そのものに重点を置き、対象の振る舞いや操作が対象の属性として備わるという考え方に基づいてプログラミングすること。プログラムの再利用が容易になり、ソフトウェアの生産性を高めることができる。

RubyにおけるObject

  • 全てがオブジェクト

インスタンスオブジェクト(インスタンス/オブジェクト)

  • データを表現する基本的な単位とデータの処理の集まり > 各種クラスからnewすることでRuby実行空間に生み出されるデータ型
String.new  =>  " "

Stringクラス  文字列オブジェクト

クラスオブジェクト(クラス)

  • オブジェクトの種類を表すもの!!オブジェクトの雛形 > オブジェクトの振る舞いを決める!!

たい焼き

  • たい焼きを焼く時の型 => クラス
  • 出来上がったたい焼き => インスタンス

たい焼きの型(クラス)をもとにたい焼きというインスタンスが作られる。

クラスとインスタンス

Stringクラスという設計図からできたインスタンス、実体

'Hello World'

上記の'Hello World'という文字列は、String クラスという設計図からつくられた、インスタンス、文字列オブジェクト

オブジェクトとしてのクラス

クラスはオブジェクトの雛形であり、クラスはオブジェクトの振る舞いを決める

ここで話がおかしくなる。
クラス自体もオブジェクトであるということ!!!

オブジェクトには✖︎✖︎クラスというクラスから成り立つ=>その︎✖︎✖︎クラスにもClassクラスというクラスから成り立っている

* String.class => Class
* Hash.class => Class
* Array.class => Class
* Numeric.class => Class

要するに?

  • あらゆるクラスはClassという一つのクラスから作られる。
  • あらゆるクラスは、Classクラスのインスタンス、オブジェクトということ!!

継承

親クラス(スパークラス)から機能を受け継ぐ

  • 既存の機能はそのままで、新たな機能を追加したい時
  • 既存の機能に処理を追加し、拡張したい時

class Person
  def initialize(name)
    @name = name
  end

  def name
    @name
  end
end

class PersonCharacter < Person  # Personクラスのサブクラス(Personを継承している)
  def initialize(name, age, sex)
    super(name)
    @age = age
    @sex = sex
  end

  def age
   @age
  end

  def sex
    @sex
  end
end

me = PersonCharacter.new('tun', 25, 'man')
puts me.name #=>tun
puts me.age #=>25
puts me.sex #=>man

モジュールオブジェクト(モジュール)

  • クラスによく似たオブジェクト > Module.class => Class

クラスとの相違点

  • モジュールはインスタンスを持つことができない
  • モジュールは継承できない=>Mix-in

Mix-in

モジュールによる機能追加 => モジュールをクラスに混ぜ合わせるMix-in

 module MyModule
  # 共通機能、処理
end

class MyClass
  include MyModule # =>これがMix-inによるモジュール機能追加
  # MyClassの固


* コメントでの指摘箇所は修正済み

module Behavior
  def self.description
    "I'm a Behavior Module"
  end

  def sleep
    "I'm sleeping"
  end

  def eat
    "I'm eating"
  end
end

class Person
  def initialize(name)
    @name = name
  end

  def name
    @name
  end
end

class PersonCharacter < Person # Personクラスのサブクラス
  include Behavior
  def initialize(name, age, sex)
    super(name)
    @age = age
    @sex = sex
  end

  def age
   @age
  end

  def sex
    @sex
  end
end

me = PersonCharacter.new('龍頭', 22, 'man')
puts me.name #=>龍頭
puts me.age #=>22
puts me.sex #=>man
puts me.eat #=>I’m eating

この他にも?

rubyは全てがオブジェクト!!

例えば nil true falseなどもすべてがオブジェクトである。

一言でオブジェクト指向プログラミング

自分なりの解釈

オブジェクトという部品を組み合わせていくプログラミング手法

オブジェクト指向というのは概念的な話であるから、ひとそれぞれ受け止め方が変わってくるのかなーってかんじる。ひとまず自分のなかでのオブジェクト指向とはと聞かれるとこのように答える。

最後まで読んでいただきありがとうございます。
なにか間違っていることなどあればご指摘お願いいたします。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0