Permalink
Browse files

add cai_methods

  • Loading branch information...
1 parent d3b0d6a commit 888a292704f860b5572e58ebaebfa00c308161c5 @lgmkr committed Oct 1, 2011
Showing with 73 additions and 0 deletions.
  1. +19 −0 class_and_instance/cai_methods_01.rb
  2. +27 −0 class_and_instance/cai_methods_02.rb
  3. +27 −0 class_and_instance/cai_methods_03.rb
@@ -0,0 +1,19 @@
+class Foo
+ def initialize
+ p "Hello Foo class!"
+ end
+
+ def self.bar
+ 'class method'
+ end
+
+ def baz
+ 'instance method'
+ end
+end
+
+# Foo.bar # => "class method"
+# Foo.baz # => NoMethodError: undefined method ‘baz’ for Foo:Class
+
+# Foo.new.baz # => instance method
+# Foo.new.bar # => NoMethodError: undefined method ‘bar’ for #<Foo:0x1e820>
@@ -0,0 +1,27 @@
+# Way 1
+class Foo
+ def self.bar
+ 'class method'
+ end
+end
+
+p Foo.bar # "class method"
+
+# Way 2
+class Foo
+ class << self
+ def bar
+ 'class method'
+ end
+ end
+end
+
+p Foo.bar # "class method"
+
+# Way 3
+class Foo; end
+def Foo.bar
+ 'class method'
+end
+
+p Foo.bar # "class method"
@@ -0,0 +1,27 @@
+# Way 1
+class Foo
+ def baz
+ 'instance method'
+ end
+end
+
+p Foo.new.baz # "instance method"
+
+# Way 2
+class Foo
+ attr_accessor :baz
+end
+
+foo = Foo.new
+foo.baz = 'instance method'
+p foo.baz
+
+# Way 3
+class Foo; end
+
+foo = Foo.new
+def foo.baz
+ 'instance method'
+end
+
+p foo.baz # "instance method"

0 comments on commit 888a292

Please sign in to comment.