[2022][ruby][7.x] refactoring

pull/1/head
Alpha Chen 1 year ago
parent fac81cb212
commit 1fa98d82d6
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -1,21 +1,19 @@
input = ARGF.read.lines(chomp: true).slice_when { _2.start_with?(?$) } input = ARGF.read.lines(chomp: true)
Dir = Struct.new(:parent, :name, :children) do Dir = Struct.new(:parent, :name, :children) do
include Enumerable
def size = children.sum(&:size) def size = children.sum(&:size)
def each(&block) def each
return enum_for(__method__, &block) unless block return enum_for(__method__) unless block_given?
block.(self) yield self
children.each do |child| children.each do |child|
case child case child
when Dir when Dir
child.each(&block) child.each { yield _1 }
when File when File
block.(child) yield child
else else
fail child.inspect fail child.inspect
end end
@ -28,9 +26,8 @@ File = Struct.new(:parent, :name, :size)
root = Dir.new(nil, ?/, []) root = Dir.new(nil, ?/, [])
pwd = root pwd = root
input.each do |chunk| input.each do |line|
cmd, *out = *chunk case line
case cmd
when /\$ cd \// when /\$ cd \//
# no-op # no-op
when /\$ cd \.\./ when /\$ cd \.\./
@ -38,18 +35,13 @@ input.each do |chunk|
when /\$ cd (.+)/ when /\$ cd (.+)/
pwd = pwd.children.find { _1.name == $1 } pwd = pwd.children.find { _1.name == $1 }
when /\$ ls/ when /\$ ls/
out.each do |line| # no-op
case line when /dir (.+)/
when /(\d+) (.+)/ pwd.children << Dir.new(pwd, $1, [])
pwd.children << File.new(pwd, $2, $1.to_i) when /(\d+) (.+)/
when /dir (.+)/ pwd.children << File.new(pwd, $2, $1.to_i)
pwd.children << Dir.new(pwd, $1, [])
else
fail line
end
end
else else
fail chunk.inspect fail line
end end
end end

Loading…
Cancel
Save