「Ruby」Dir.foreachでフォルダ内のファイルを取得する

2021年12月24日

環境情報
# cat /etc/debian_version
11.2
# ruby -v
ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x86_64-linux-gnu]

書式
Dir.each_child(“ファイルパス")
Dir.each_childを使用すれば、フォルダ内のファイルを全て表示します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Dir.each_child("/data").each do |i|
p i
end
Dir.each_child("/data").each do |i| p i end
Dir.each_child("/data").each do |i|
  p i
end

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# ruby sample4.rb
"sample.rb"
"test.php"
"sample."
"test.doc"
"sample.txt"
"sample2.rb"
"sample4.rb"
# ruby sample4.rb "sample.rb" "test.php" "sample." "test.doc" "sample.txt" "sample2.rb" "sample4.rb"
# ruby sample4.rb
"sample.rb"
"test.php"
"sample."
"test.doc"
"sample.txt"
"sample2.rb"
"sample4.rb"

 

Ruby

Posted by arkgame