跳到主要内容

跟着 chatgpt 与开源代码学习 ruby

2023-05-18

跟着chatgpt看开源代码学习新语言, 实测掌握速度非常快, 能够快速补全在新语言中缺失的知识版图.

遗憾的是, 过了几个星期再次翻阅, 发现很多语法细节又忘得差不多了. 不使用的话, 大多数编程的边角知识其实都会快速被遗忘, 所以很多人都在反反复复. 但是不用慌, 只要掌握大概原理, 知道整体框架, 知道怎么提问, 并且晓得去看开源代码快速提高就行. 学习了就用起来, 至少还留下点积累和痕迹.

https://github.com/larskanis/pg-ldap-sync

ruby 基础语法

学习新语言新语法的时候, 比较麻烦的是各种新的符号含义, 在搜索引擎里搜这些符号很难直接得到自己想要的.

  • ||符号
def add(severity, *args, &block)
super
return unless [Logger::FATAL, Logger::ERROR].include?(severity)
@counters[severity] ||= block ? block.call : args.first
end

picture 23

picture 36

  • :: 类定位

class Logger < ::Logger
def initialize(io)
super(io)

picture 3

  • ! 感叹号

这段的代码什么意思, 尤其是两个感叹号

def had_logged?(severity)
!!@counters[severity]
end

picture 4

picture 35

  • *
system( *cmd ) 

picture 24

  • $?.success?

picture 7

  • [:out, :err] => [fname, "w"]

picture 8

picture 9

  • File.unlink fname rescue nil

picture 10

  • <=>, #{}=~

picture 31

  • hash_of_arrays = Hash.new { |h, k| h[k] = [] }

默认映射表值

picture 37

  • inject
ldap_by_dn = ldap_roles.inject(hash_of_arrays){|h,r| h[r.dn] << r; h }

picture 38

yield 参数

picture 21

ruby 正则语法

picture 30

picture 32

if ranged_attr =~ /;range=\d\-\*\z/

picture 33

  • gsub
attribute_with_range = ranged_attr.to_s.gsub(/;range=.*/, ";range=#{array.size}-*")

picture 34

如何运行ruby

picture 18

ruby 依赖管理体系

ruby中有bundler, gem, rake这些常用的依赖管理工具, 看起来比python和node要复杂一些, 得使用多几次才能记住.

不过大体可以认为gem等同于python的pip命令, bundler则类似于python的virtualenv提供虚拟环境管理.

picture 26

gem 依赖包管理

gem 基础使用

picture 25

picture 17

picture 22

gemfile.lock文件与gemfile配置不同环境使用不同的版本

![picture 13](/assets/2023-06/2023060 4072702-22136.png)

gem包可以被作为依赖安装使用

picture 29

gem包可以被直接运行

picture 28

bundler 依赖管理工具

picture 12

rake 自动化构建工具

picture 14

Rake::TestTask.new(:test) do |t|
t.libs << "test"
t.libs << "lib"
t.test_files = FileList["test/**/test_*.rb"]
end

task :gem => :build

picture 15

picture 16

picture 27

ruby postgreql

  • 命令行启动postgresql

chatgpt 给出了错误的代码, 进行质疑后, 又能直接修改.

picture 11


pg_ctl - initialize, start, stop, or control a PostgreSQL server
-W
--no-wait
Do not wait for the operation to complete. This is the opposite of the option -w.

If waiting is disabled, the requested action is triggered, but there is no feedback about its success. In that case, the server log file or an external monitoring system would have to be used to check the progress and success of the operation.

In prior releases of PostgreSQL, this was the default except for the stop mode.

ruby minitest 测试库

picture 19

picture 20