Sorry ,i am not show it very clear.Please read this example again:
class Test
def Test.say_hello
puts "Hello from #{self.name}"
puts "hello from #{self.class}"
end
say_hello #i don't understand here
ok I see now, well this is "simple" once you have grasped the concept,
but quite difficult before -- as so often
It might be helpful to grasp the concept of self before, I'd advice
Pickaxe for that
http://www.ruby-doc.org/docs/ProgrammingRuby/
now in Ruby there is always a self defined, the implicit receiver to
which unqualified messages are sent
Fire up your irb to learn a little bit more about that
536/37 > irb
irb(main):001:0> self
=> main
# This is the default self provided by the Ruby Interpreter
irb(main):002:0> class Test
### look what happens to self when inside a class statement
irb(main):003:1> puts self
irb(main):004:1> end
Test
=> nil
irb(main):005:0> class Test
### say_hello is sent to self, which is Test in this context
irb(main):006:1> say_hello
### but Test does not reply to this message yet
irb(main):007:1> end
NameError: undefined local variable or method `say_hello' for Test:Class
from (irb):6
from :0
irb(main):008:0> class Test
### The def statement defines an *instance* method on self, we have therefore
### to write Test.say_hello in order to tell def a method on Test
itself, but you
### seem to know that already
irb(main):009:1> def Test.say_hello
irb(main):010:2> puts "Hello"
irb(main):011:2> end
irb(main):012:1> end
=> nil
irb(main):013:0> class Test
### self is set to Test again and now Test responds to the #say_hello message
irb(main):014:1> say_hello
irb(main):015:1> end
Hello
=> nil
### and just to show that the main object was not influenced by what
we defined for Test
irb(main):020:0> say_hello
NameError: undefined local variable or method `say_hello' for main:Object
from (irb):20
from :0
irb(main):021:0>
end
Normally,we can use a class anyplaces after defining it ,but in this
example,i use a classmehod immediately after defining it "in class
context".This is valid.I means calling a classmethod(not an intance
method) in a class defintion--not after defining that class--is valid
.Can you explain it for me? thank you !
Funny but you explained it quite well, if there were no ? I would say
you have made a correct statement. Maybe you are just puzzled by the
dynamic nature of Ruby that everything springs into life when
executed.
class Test
dosomething
end
as a matter of fact is equivalent to
Test = Class::new
class Test
#(1)
doesomething
end
meaning that at point (1) Test is a well defined complete Ruby class already
HTH
Robert