[Ruby笔记]22.Ruby :: namespace 以及 instance method 与class method

本文探讨了Ruby中的`::`命名空间及其在增强代码可读性方面的作用。同时,区分了实例方法和类方法的定义及调用方式,包括它们在类定义内外的使用,并提供了参考书籍《The Well-Grounded Rubyist, Second Edition》的相关章节。" 5501845,8973,Ubuntu9.10安装文泉驿微米黑字体指南,"['Ubuntu', '字体管理']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

:: 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值