Ruby 惯用模式
DSL 构建、tap/yield_self、安全导航 &、%w/%i 字面量
Ruby 惯用模式
Ruby 社区沉淀了许多惯用法——tap/yield_self、&. 安全导航、%w/%i 字面量、DSL 构建。
学完本章你将: 掌握 tap/yield_self、安全导航、% 字面量、DSL。
tap / yield_self / then
ruby
# tap —— 在方法链中"偷看"中间值
user = User.new.tap { |u| u.name = "小明" }.tap { |u| u.save }
# yield_self / then —— 把对象传给块并返回结果
"hello".then { |s| s.upcase }.then { |s| s + "!" }
# => "HELLO!"
安全导航 &.
ruby
# 替代 if user && user.address && user.address.city
city = user&.address&.city
# 也可用于方法调用
user&.name&.upcase
% 字面量
ruby
%w[apple banana cherry] # ["apple", "banana", "cherry"](字符串数组)
%i[apple banana cherry] # [:apple, :banana, :cherry](Symbol 数组)
%q[不需要转义 ' 和 "] # 单引号字符串
%Q[可以插值 #{name}] # 双引号字符串
%r{正则} # 正则
构建 DSL
ruby
class HTML
def initialize(&block)
instance_eval(&block) if block
end
def tag(name, &block)
puts "<#{name}>"
block.call if block
puts "</#{name}>"
end
end
HTML.new do
tag :html do
tag :body do
puts "Hello"
end
end
end