目次
インスタンス変数のスコープ
class MyClass @v = 1 def foo @V end class << self @v = 2 def foo @v end end end MyClass.foo # => 1
2が出力されそうだが、1が出力される
クラス変数はサブクラスでも共有される
class C @@count = 0 def initialize() @@count += 1 end def class_variable @@count end end class D < C end C.new c = C.new D.new d =D.new c.class_variable # => 4 d.class_variable # => 4
Foo::fooでメソッド呼び出しが可能
class Foo def self.foo puts "foo" end end Foo::foo # => foo self.foo # => NoMethodError: undefined method `foo' for main:Object
可変長引数はなくてもエラーにならない
class Foo def test(*arg) end end Foo.new.test() # => nil
refinements
class A def foo puts "A" end end class B < A def foo super puts "B" end end module M refine B do def foo super puts "M" end end end b = B.new b.foo # => A # => B using M b.foo # => A # => B # => M
例外処理
begin "John".cooking rescue NameError => e puts e.class # NoMethodError を表示 end
includeの位置で変わる
module M @@x = 100 end class A @@x = 500 include M end module M puts @@x # 100 と表示される end class A puts @@x # 500 と表示される end
module M @@x = 100 end class A include M @@x = 500 end module M puts @@x # 500 と表示される end class A puts @@x # 500 と表示される end
superとsuper()は挙動が異なる
class Hoge def hoge(arg=nil) p arg end end class Fuga < Hoge def hoge(arg) p super(5) # => 5 p super(arg) # => 10 p super # => 10 arg = 1 p super # => 1 p super() # => nil end end Fuga.new.hoge 10
コメントを残す