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

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.open(“ファイルパス")
Dir.openを使用すれば、ディレクトリ内のファイル/ディレクトリを列挙します。

使用例

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

実行結果

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

 

Ruby

Posted by arkgame