我已编写以下代码以检查用户输入字符串是否存在于文件中。该方法是 checkinfile 。我正在使用while循环逐行读取并执行.eql?检查它是否匹配。 但即使我输入匹配值,该方法返回false。有人可以帮帮我吗?
class School
#Declaration of Global Variable. The file is the file database used for storing names of the students.
$filename="studentsdatabase"
#All the methods for the class Student are declared in this area
#Method : Show Menu
def showmenu
puts "\e[H\e[2J"
print "*" * 100
print "\n"
print "-"*44 + "MENU OPTIONS" +"-"*44 + "\n"
print "*" * 100
print "\n"
print "1. Add a student data\n"
print "2. Verify if the student is present in the database\n"
print "3. View the list of students in the database"
print "Enter your option(1/2) :"
option=gets.chomp.to_i
return option
end
#Method : Ask the details of the students
def askdetails
puts "\e[H\e[2J"
print "How many students are there\n"
n = gets.chomp.to_i - 1
print "Enter names one by one\n"
names=Array.new(n)
for i in (0..n)
names[i]=gets.chomp
end
return names,n
end
def showdetails(names,n)
for i in (0..n)
puts names[i]
end
end
#Method : Write into file database
def write2file(names,n)
studnamesfile=File.open($filename,"a")
for i in (0..n)
studnamesfile.puts names[i]
end
end
#Method : This method verifies the user input in the file database.
def checkinfile
puts "\e[H\e[2J"
print "Enter the name of the student: "
studname=gets.chomp
somefile=File.open($filename,"r")
counter=1
occur=0
while(line=somefile.gets)
val = puts.eql? studname
occur=occur+1
puts "#{counter}: #{line}"
puts "#{val}"
counter = counter + 1
end
somefile.close
end
#This is the end of Class Student declaration
end
#Main Program starts here
stud=School.new
option=stud.showmenu
if option==1
names,n = stud.askdetails
stud.write2file(names,n)
else
puts "\e[H\e[2J"
stud.checkinfile
end
答案 0 :(得分:0)
这是包含eql?
:
val = puts.eql? studname
在此处检查调用方法puts
的返回值是否等于studname
。 puts
始终返回nil
,因此,val
可能始终为false
。
要解决此问题,您应该使用line
:
val = line.eql? studname
此外,您可能希望确保没有影响测试的尾随换行符:
val = line.strip.eql? studname.strip