如何在Ruby中创建一个目录

时间:2014-04-17 14:32:03

标签: ruby

所以我在Ruby中创建这个项目,我从某个地方复制了这个代码并且它无法正常工作。

代码:

dirname = File.dirname("C:/ProgramFiles/RubyLists")

require 'fileutils'

unless File.directory?(dirname)
  File.mkdir(dirname)
end  #This block will make the directory.

print("Mk. Worked.")

错误:

C:/Users/User/RubymineProjects/rubylists/main.rb:6:in `<top (required)>': undefined method `makedir' for File:Class (NoMethodError)
    from -e:1:in `load'
    from -e:1:in `<main>'

如果您需要更多信息,请告诉我,如果可以,我会提供。谢谢!

3 个答案:

答案 0 :(得分:2)

FileUtils::mkdir存在,而不是File::mkdir

因此将File.mkdir(dirname)更改为FileUtils.mkdir(dirname)

编写代码: -

dirname = "C:/ProgramFiles/RubyLists"

require 'fileutils'

unless Dir.exist?(dirname)
  FileUtils.mkdir(dirname)
end  #This block will make the directory.

print("Mk. Worked.")

答案 1 :(得分:2)

由于您使用的是FileUtils,因此可以使用mkdir

FileUtils.mkdir("a/b/c")

但是如果任何父文件夹不存在,它就会崩溃。我通常使用mkdir_p,因为它会根据需要递归创建目录(除非我希望它崩溃,例如,如果文件夹名称错误)

答案 2 :(得分:1)

# function for create folder
def createFolder(folderName)
@folderName=folderName
  if File.directory?(@folderName)
  return "The Folder "+@folderName+" already exist"
  else
  Dir.mkdir(@folderName,0700)
  return "Created"
  end
end 

调用它只需输入

createFolder('folderName')