LoginSignup
1
1

More than 3 years have passed since last update.

オブジェクト クラス module

Last updated at Posted at 2019-10-05

オブジェクト

  • 初期設定
  • メソッド
# 初期設定(initialize, accessor)
# メソッド

class Foo 
  attr_accessor :name, :yahoo
  def initialize(name, yahoo)
   @name = name
   @yahoo = yahoo
  end

  def hello
    @name + ":" + @yahoo
  end

end

foo = Foo.new("name", "yahoo")

 p foo.name
 p foo.yahoo
 p foo.hello

継承

class Parent

  def hello
   "hello"
  end

end

class Child < Parent

end

c = Child.new
p c.hello
  • super
class Parent

  def hello
   "hello"
  end

end

パターン①

class Child < Parent
  def hello
    super
  end
end

c = Child.new
p c.hello

→ "hello"

パターン②

class Child < Parent
  def hello
    "yahoo"
  end
end

c = Child.new
p c.hello
→ yahoo

クラスメソッド

  • self
  • class << self; end
class Hoge


 def self.hello
  "hello"
 end
end

p Hoge.hello

class Hoge

 class << self
  def hello
    "hello"
  end
 end
end

p Hoge.hello

公開非公開

  • public
    • インスタンスメソッドとして呼び出せる
  • private  - インスタンスメソッドから(内部から)呼び出す  - 内部のメソッド内で処理に使うメソッド
class Hoge
 def public_method
  p "public_method"
  private_method("hello")
 end

 private 

 def private_method(aa)
   "private_method" + aa
 end
end


p Hoge.new.public_method

ネストした定数

  • 定数
  • ネスト

module M1
 class Hoge
  p "module"
 end
end


p M1::Hoge
→ "module"
::M1::Hoge #どっちでもいける

p ::M1.constants
→ [:Hoge]

method_missing メタプログラミング

  • superで method_missingをオーバーライドしてる

class Hoge
  def method_missing(m, *args)
    p "called:" + m.to_s
    super
  end
end

Hoge.new.kuso_method

module

理由

  • 単一継承をクラスはできない
# 多重継承?
# Hoge < Memo, Emo????

class Memo
 def aaa

 end

end

class Hoge < Memo
  include Bar

end

解決策

  • module
    • module定義
    • include
module Bar
 def yahoo
  "yahoo"
 end
end

class Hoge < Memo
  include Bar

end


p Hoge.new.yahoo
  • 実行順番

module M1
 def yahoo
  "M1"
 end
end

module M2
  def yahoo
    "M2"
  end
end

class Hoge 
  include M1 #実行2
  include M2 #実行1

end


p Hoge.new.yahoo
1
1
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
1