./ruby/classes.txt
download original
see: "programming ruby", section "classes and objects"
irb(main):022:0> def callf(obj)
irb(main):023:1> obj.f
irb(main):024:1> end
nil
irb(main):025:0> s="hello"
"hello"
irb(main):026:0> callf(s)
NameError: undefined method `f' for "hello":String
from (irb):23:in `callf'
from (irb):26
irb(main):027:0> class <<s
irb(main):028:1> def f
irb(main):029:2> p "i am s.f!"
irb(main):030:2> end
irb(main):031:1> end
nil
irb(main):032:0> callf(s)
"i am s.f!"
nil
irb(main):033:0>
### class method inheritance
21:04 -!- multi_io [~olaf@swangoose.isst.fhg.de] has joined #ruby-lang
21:08 < multi_io> hmm.. it appears that class methods defined in a module
(using "def self.bla ... end") are not inherited by classes
that include that module, but class methods defined in a
class are inherited by classes deriving from that class. Is
that right?
21:10 < sam-> multi_io: that's correct. To get class methods from a module,
you need to extend the module, not include it
21:12 < multi_io> sam-: you mean I need to extend (with the module) the class
that should receive the module's class methods?
21:15 < sam-> multi_io: right, except it's actually the instance methods of the
module which become class methods on the class that extends the
module
21:15 < sam-> module Foo; def bar() "baz" end end
21:15 < sam-> class Quux; extend Foo; end
21:15 < sam-> Quux.bar #=> "baz"
21:16 < multi_io> sam-: OK
21:17 < sam-> the best way to figure it out is to open up irb and play around
21:22 < multi_io> sam-: I do that all the time, of course :)
21:23 < sam-> I love irb :)
21:23 * flowhase too
21:23 < flowhase> especially since i found irb/completion.rb
21:24 < multi_io> I just saw in the Rails sourcecode that one can override
self.append_features to transparently add the class methods
on "include" too.
21:25 < sam-> yes
21:25 < sam-> the preferred way to do that in 1.8+ is to implement
Module#included
back to ruby
(C) 1998-2017 Olaf Klischat <olaf.klischat@gmail.com>