开发者

Require Method in Ruby

开发者 https://www.devze.com 2023-02-22 06:05 出处:网络
I have been searching around but I cant seem to find any answers for this problem. I am required to write a program that will use the reflection methods built into ruby to tell me information about a

I have been searching around but I cant seem to find any answers for this problem.

I am required to write a program that will use the reflection methods built into ruby to tell me information about a class a user will specify.

I have this method:

def validFile(input)  
  filename = String.new()  
  filename = Dir.getwd + "/" + input  
  require(filename)  
end  

however I get this error:

internal:lib/rubygems/customrequire:29:in 'require' no such file to load --         C:\Users\David\Ruby Projects\MyTestClass.rb

I am not sure why this doesn't work but this does:

def validFile(input)
  filename = Dir.getwd + "/MyTestClass.rb"
  require(filename)
end

This code doesn't help me because I have to have the user specify the file. I am using开发者_如何学运维 the gets method to get user input and that is being passed as a parameter to this method.

Are they not both strings? What am I doing wrong here? Additional note, I'm running the latest version of ruby on Windows 7. Thanks for the help.


Just in case. Have you chomped the string that you got by gets before passing it as an argument? If you havn't, then it will contain extra carriage return characters at the end. You need to remove them like input = gets.chomp


You can use File.exist?(filename) to see if a file or directory exists. This should help narrow down the problem.


Most likely, you're getting this input with gets. Either chomp it in this method or use the more common idiom of gets.chomp. So you can do something like this.

def do_require(input)
  require( Dir.getwd + "/" + input )
end

do_require gets.chomp
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号