練習 3-2
`cmd` を使って文字列を作る練習問題。
前回の修正
前回のをちょっと修正。
puts `ls -la | awk 'NF==9{printf("%s, %d\\n", $9, $5)}'` # >> ., 3366 # >> .., 204 # >> .bash_history, 507123 # >> .bash_profile, 16 # >> .bashrc, 1188 ...
NF==9 がないとゴミが出る。*1
ただしファイル名に空白が入っていると表示されなくなる。(マテ)
発展形
puts `ruby -e 'puts Dir.open(".").map{|f|"\#{f}, \#{File.size(f)}"}'` # >> ., 3366 # >> .., 204 # >> .bash_history, 507123 # >> .bash_profile, 16 # >> .bashrc, 1188 ...
エスケープがややこしいですね。
冗談はこのくらいにして、
模範回答
と思われるものを
puts `ls -la`. split(/\n/). map{|i|i.strip.split(/\s+/, 9)}. reject{|i|i[8].nil?}. map{|i|i.values_at(-1, 4).join(', ')} # >> ., 3366 # >> .., 204 # >> .bash_history, 507123 # >> .bash_profile, 16 # >> .bashrc, 1188 ...
9 とか 8 とか 4 とか -1 とか気になる。
では、こうか
LSLong = Struct.new(:perm, :ln, :uid, :gid, :size, :mon, :mday, :year_time, :name) puts `ls -la`. split(/\n/). map{|i|LSLong.new(*i.strip.split(/\s+/, LSLong.members.size))}. reject{|i|i.name.nil?}. map{|i|"#{i[:name]}, #{i[:size]}"}
やっぱりディレクトリ/ファイルの処理は Dir, File, FileUtils なんかを使う方が簡単。
*1:実際の結果を貼ってないから気付かなかった。