Reputation: 11
I need to see if a file exists, and then if it exists, I want to open the file, and see what it contains.
I have these methods:
def Utility.exist_request_xml(filexml)
puts("exist_request_xml")
if(File.exist?("#{PATH_WEBSERVICES_REQUEST}/#{filexml}"))
puts 'file exists'
puts(File.exist?("#{PATH_WEBSERVICES_REQUEST}/#{filexml}"))
else
puts 'file not exist'
end
end
def Utility.open_request_xml(filexml)
puts("open_request_xml")
if(Utility.exist_request_xml(filexml))
f=File.open("#{PATH_WEBSERVICES_REQUEST}/#{filexml}","r")
f.each_line do |line|
puts line
end
else
puts 'there is no file to open'
end
end
The first method works. I cannot open the file in the second method. The problem is that, even if the file exists, because I recall the first method in the second, it doesn't open the file.
Can you help me?
Upvotes: 0
Views: 87
Reputation: 22375
Your Utility.exist_request_xml
method returns nil
, which is falsey in an if
statement, so it falls through to the else where you don't open the file.
It returns nil
because by default the last evaluated expression is the return value and your last expression is an if. Similarly the return value of an if is the last thing it evaluates, which is a puts
(in either branch). puts
returns nil
.
Return the value of the existence check instead:
def Utility.exist_request_xml filexml
File.exist? "#{PATH_WEBSERVICES_REQUEST}/#{filexml}"
end
Upvotes: 6