1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

初めてのRuby4   〜オブジェクト指向〜

Last updated at Posted at 2019-07-05

オブジェクト指向

:point_up_tone1:オブジェクト指向とはプログラミングを書くときの基本となる考え方。
プログラムの処理の対象をオブジェクトとして考える。
(オブジェクトはデータ(変数)と手続き(メソッド)をまとめたもののこと)

pablicとprivate

:eye:オブジェクト指向プログラミングではそれぞれのオブジェクトを外部に公開するかしないか制御する必要がある。
→メソッド一つ一つについて、公開・非公開を変更することができる:information_desk_person_tone2:

例.
class AccessTest
 public
 def show 
   puts "public"
 end

 private
 def secret
  puts "private
 end
end


obj = AccessTest.new
obj.show => "public"
obj.secret :x:

:star:public : 以降のメソッドを公開にする。記述なしの場合はデフォルトでpublic
:star:private : 以降のメソッドを非公開にする。オブジェクトの外部からは呼び出せない。


:snowflake:オブジェクトの内部 : オブジェクトクラスのメソッドの中(classからendまで)
:snowflake:オブジェクトの外部 : 内部以外のとこ

attr_族

:sunny:attr_accessor

インスタンス変数を読み書きするメソッドを提供する文

class Recipe
 attr_accessor :title
end

recipe = Recipe.new
recipe.title = "cheese cake"
p recipe.title => "cheese cake"

下記とイコール

class Recipe
 def title = (t)
  @title = t
 end
 def title  
  @title 
 end

recipe = Recipe.new
recipe.title = "cheese cake"
p recipe.title => "cheese cake"
:sunny:attr_reader

読み込み用の公開メソッドを用意

class Recipe
 attr_reader :title
end

recipe = Recipe.new
p recipe.title

以下とイコール

class Recipe
 def title
  @title 
 end
end

recipe = Recipe.new
p recipe.title
:sunny:attr_writer

書き込み用の公開メソッドを用意

class Recipe
 attr_writer :title
end

recipe = Recipe.new
p recipe.title

以下とイコール

class Recipe
 def title = (t)
  @title = t
 end
end

recipe = Recipe.new
p recipe.title

継承

すでに定義されているクラスを拡張して他のクラスの定義とする

例)BookクラスとMagazineクラスを作る。二つには共通することがある

class Book
 attr_accessor :genre, :price
end
class Magazine
 attr_accessor :genre, :price, :title
end

この場合、Magazineクラスを↓のようにしても同じ

class Magazine < Book
 attr_accessor :title
end

:helmet_with_cross:class Magazine < Book によりMagazineクラスはBookクラスの性質を受け継ぐことができる。

:writing_hand_tone1:書き方

class クラス名 < 親クラス名
 クラスの定義
end

:point_up_2_tone1:継承したクラスは親クラスの全てのインスタンス変数、メソッドなどを受け継ぐ。

コーディングの際は重複が多くならないようにする

→動作を変更したい時にたくさん書き換えなきゃいけなくなるので・・:frowning2:

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?