以前写 CSV 最讨厌的就是把每一行数据和变量名对应起来,特别是遇到 CSV 文件的列数非常多的情况。发现一个小 Tip,用并行赋值的写法处理起来非常方便....
之前写法:
CSV.foreach("csv_path") do |row|
title = row[0]
desc = row[1]
name = row[2]
# handle title, desc name
end
并行赋值:
CSV.foreach("csv_path") do |row|
title, desc, name, * = row
# handle title, desc, name
end
并行赋值还有哪些应用?
CSV.foreach("csv_path") do |(title, desc, name, *rest)|
# handle title, desc, name
end
_, date, urlname, _ = *filename.match(/\A#{tmp_path}\/_posts\/(\d+-\d+-\d+)-(.+)(\.[^.]+)\z/)
解析 jekyll post 的文件名。
#10 楼 @hooopo 你需要的是一门原生支持 pattern matching 的语言,比如,badmatch https://github.com/bhuztez/badmatch
/\A#{tmp_path}\/_posts\/(?<date>\d+-\d+-\d+)-(?<urlname>.+)(\.[^.]+)\z/ =~ filename
然后 date 和 urlname 都在局部变量里了
#14 楼 @bhuztez 其实 ruby 的 case
语句已经很接近了
case [x, y, z]
when [x, x, x] then :equilateral
when [x, x, z], [x, z, z] then :isosceles
else :scalene
end
给 Array
加个解构匹配方法就更差不多了
class Array
def === other
size == other.size and
zip(other).all? do |e, oe|
e === oe
end
end
end
foo = 3
case [foo, "bar"]
when [Integer, "bar"] then puts "matched"
end
irb(main):001:0> case [1,2,3] when [x,y,z] then puts "ok" end
NameError: undefined local variable or method `x' for main:Object
from (irb):1
from /usr/bin/irb:12:in `<main>'