Ruby Ruby 标准库有趣部分摘要

Mark24 · 2021年12月07日 · 最后由 Mark24 回复于 2021年12月09日 · 930 次阅读

我的 BLOG https://mark24code.github.io/ruby/2021/12/07/Ruby%E6%A0%87%E5%87%86%E5%BA%93%E6%9C%89%E8%B6%A3%E9%83%A8%E5%88%86%E6%91%98%E8%A6%81.html

摘要

  • etc 用来获得 /etc 下面信息。比如系统登录用户,可以做一个系统粘合性较高的程序来使用。
  • enumerable 把你的 class 变成迭代器
  • objectspace 可以返回 class 实例统计信息,size 等,可以作为扫描、performance、统计使用。
  • observable 把你的 class 变成发布订阅模式
  • marshal 把程序对象字节持久化,或者还原。适合做在内存中缓存对象。比如 命令模式栈里撤销的对象。
  • pathname 有野心的 module 封装了路径的操作,方便目录文件操作
  • IO#eof? eof?是一个外部迭代器可以用的方法,外部迭代器更方便控制。其他eof? 同理。
  • mutex 多线程中提供锁同步
  • drb 让 Ruby 支持分布式程序,通过 TCP/IP 将程序各部分合并在一起。
  • forwardable 自动生成代理方法。

这个要介绍下比如

require 'forwardable'

class WriterDecorator
  extend Forwardable

  def_delegators :@real_writer, :write_line #, :other_method .... 方法不限制

  def initialize(real_writer)
    @real_writer = real_writer
  end

end

就会生成类似如下的部分。

def_delegators 接受两个或者更多参数,第一个是实例属性的名字,后面是一个或者多个方法的名字,每个方法都会被传递到代理对象上去。

forwardable 是比 method_missing 更精确的武器。

class WriterDecorator
 def initialize(real_writer)
   @real_writer = real_writer
 end

 # 传递代理方法
 def write_line(line)
   @real_writer.write_line(line)
 end
end



#0:<internal:lib/rubygems/custom_require>:38:Kernel:<: -
#0:example.rb:3::-: class A
#0:example.rb:3::C: class A
#0:example.rb:4::-:   def square(a)
#0:example.rb:7::E: end
#0:example.rb:9::-: a = A.new
#0:example.rb:10::-: a.square(5)
#0:example.rb:4:A:>:   def square(a)
#0:example.rb:5:A:-:     return a*a
#0:example.rb:6:A:<:   end
 |  |         | |  |
 |  |         | |   ---------------------+ event
 |  |         |  ------------------------+ class
 |  |          --------------------------+ line
 |   ------------------------------------+ filename
  ---------------------------------------+ thread

Symbol table used for displaying incoming events:

+}+:: call a C-language routine
+{+:: return from a C-language routine
+>+:: call a Ruby method
+C+:: start a class or module definition
+E+:: finish a class or module definition
+-+:: execute code on a new line
+^+:: raise an exception
+<+:: return from a Ruby method

  • singleton 把你的 class 变成单例模式

未完待续

etc 这种应该移除标准库。。。

还有类似 cgi 这种,现在估计没人用了吧。。。python 都开始清理了。

好像已经移出去了。😄

Ruby 在标准库上的维护挺好的 [^ruby],反观隔壁 [^python],真是一言难尽……

[^ruby]: Ruby's standard library is in the process of being gemified. More and more libraries will be turned into RubyGems, which can be updated independently from Ruby. https://stdgems.org/

[^python]: PEP 594 -- Removing dead batteries from the standard library https://discuss.python.org/t/pep-594-removing-dead-batteries-from-the-standard-library/1704

我其实觉得有高质量的标准库挺好的。

JavaScript 就不存在高质量、标准库。所以各种代码的操作都极大地围绕周边第三方仓库。一些简单的事情也很复杂。百里不同样。 第三方也可能不维护了。这样说可能有些人都没有概念。比如处理时间,JS 是没有自己完善的标准库的。需要仰赖第三方,那你选择就多了 moment、date-fns ……简单的事情,可能每个仓库不同人经手口味不同。

简单的事情也变复杂了。

这个角度,我其实很欣赏官方愿意花精力维护一些标准库。

而且 Ruby 的标准库范围很广,让我觉得很有趣。 etc 的存在,意味着,你去写一些命令行的程序也很方便。操作系统方面兼容性的细碎不是一般小白,或者我就想快速做一个脚本。这样的人可以搞定的。

Mark24 回复

官方维护接口就行了。 😂

需要 登录 后方可回复, 如果你还没有账号请 注册新账号