:: namespace
在module
里面放了一个class
,要实例化这个class
,需要用M::C.new
, module M
起到了namespace
的作用,从视觉上大大加强代码的可读性:
PS C:\Users\Administrator> irb --simple-prompt
>> module M
>> class C
>> end
>> end
=> nil
>> t = M::C.new
=> #<M::C:0x0000000301e340>
instance method vs class method
instance method
写在类的定义里面
>> class A
>> def say_hello
>> puts "hello"
>> end
>> end
=> :say_hello
class method
可以不用写在类的定义里
>> def A.good
>> puts "good day"
>> end
=> :good
::
调用class method
>> A::good
good day
=> nil
>> A.good
good day
=> nil
- 常见的用法
>> Math::PI
=> 3.141592653589793
>> Math::E
=> 2.718281828459045
- 创建一个对象,然后调用
instance method
>> a = A.new
=> #<A:0x000000030a1a38>
>> a.say_hello
hello
=> nil
reference
《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
3.7. Constants up close
4.4.2. Nesting modules and classes
`∧_∧
(;´Д`)
( つ と)
と_)_)
http://emoji.vis.ne.jp/ase_ase40.htm