1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | irb(main):092:0> class Cat irb(main):093:1> end => nil irb(main):087:0> c = Cat.new => #<Cat:0x2bacb68> irb(main):088:0> c.class => Cat irb(main):089:0> c.class.superclass => Object irb(main):090:0> c.class.superclass.superclass => nil irb(main):091:0> c.class.superclass.superclass.superclass NoMethodError: undefined method `superclass' for nil:NilClass from (irb):91 from :0 |
1 2 3 4 5 6 7 8 | irb(main):100:0> 1.class => Fixnum irb(main):101:0> 1.class.superclass => Integer irb(main):102:0> 1.class.superclass.superclass => Numeric irb(main):103:0> 1.class.superclass.superclass.superclass => Object |
1 2 3 4 5 6 | irb(main):100:0> String.class => Class irb(main):101:0> String.class.superclass => Module irb(main):102:0> String.class.superclass.superclass => Object |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | irb(main):020:0> module MyModule irb(main):021:1> def hello irb(main):022:2> puts "Hello World" irb(main):023:2> end irb(main):024:1> end irb(main):025:0> test = MyModule.new NoMethodError: undefined method `new' for MyModule:Module from (irb):25 irb(main):026:0> class MyClass irb(main):027:1> include MyModule irb(main):028:1> end => MyClass irb(main):029:0> test = MyClass.new => #<MyClass:0x2c18bc8> irb(main):030:0> test.hello Hello World => nil |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | irb(main):113:0> y = Human.new => #<Human:0x319b6f0> irb(main):114:0> def y.paint irb(main):115:1> puts "Can paint" irb(main):116:1> end => nil irb(main):117:0> y.paint Can paint => nil irb(main):118:0> z = Human.new => #<Human:0x3153fc0> irb(main):119:0> z.paint NoMethodError: undefined method `paint' for #<Human:0x3153fc0> from (irb):119 |
1 2 | irb(main):120:0> y.singleton_methods => ["paint"] |
1 2 3 4 5 6 7 8 9 10 11 | irb(main):113:0> y = Human.new => #<Human:0x319b6f0> irb(main):114:0> class << y irb(main):115:1> def sing irb(main):116:1> puts "Can sing" irb(main):117:1> end irb(main):118:1>end => nil irb(main):117:0> y.sing Can sing => nil |
1 2 3 4 5 6 7 8 9 10 11 | irb(main):035:0> y = String.new("racecar") => "racecar" irb(main):036:0> y.methods.grep(/palindrome/) => [ ] irb(main):037:0> class String irb(main):038:1> def palindrome? irb(main):039:2> self == self.reverse irb(main):040:2> end irb(main):041:1> end irb(main):050:0> y.palindrome? => true |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class SelfTest def self.test puts "Hello World with self!" end end class SelfTest2 def test puts "This is not a class static method" end end SelfTest.test SelfTest2.test |
1 2 3 4 5 6 | irb(main):087:0> SelfTest.test Hello World with self! => nil irb(main):088:0> SelfTest2.test NoMethodError: undefined method 'test' for SelfTest2:Class from (irb):88 |
1 2 3 4 5 6 7 | class TestMe def TestMe.test puts "Yet another static member function" end end TestMe.test # works fine |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |