如何解决读写文件和条件语句的大小
初学者学习Ruby。正在做关于读写文件的练习。
name_number = {
}
File.open("book.txt",'a') do |file|
name_number.each do |name,number|
file.write ("- #{name} #{number}\n")
end
file.close
end
File.open("book.txt","r") do |file|
if file.size < 1
puts "There are no people in the book."
end
File.open("book.txt","r") do |file|
puts file.read
end
end
因此它输出“书中没有人”。当文件为空时。
所以,如果我们增加一些人...
name_number = {
"Bill" => 87987,"Kevin" => 78912
}
File.open("book.txt",number|
file.write ("- #{name} #{number}\n")
end
file.close
end
我试图弄清楚怎么说
“有一个人”代表1 和“有人”超过1的数字。
我想我需要一个elsif
这样的语句(但显然这没有用,但是也许您可以看到我在想达到的目标?)。
File.open("book.txt","r") do |file|
if file.size < 1
puts "There are no people in the book."
elsif file.size == 1
puts "There is an entry in the book."
elsif file.size == 2
puts "There are two entries in the book"
end
File.open("book.txt","r") do |file|
puts file.read
end
end
我肯定错过了一些东西。我想知道是否有人可以指出我正确的方向?
解决方法
file.size为您提供字节数。您可能需要file.readlines。size
,我发现如果我将 .count 与 readlines 一起使用,就能解决我的问题!
更新的代码
File.open("book.txt","r") do |file|
number = file.readlines.count
if number < 1
puts "There are no people in the book."
elsif number == 1
puts "There is one person in the book"
File.open("book.txt","r") do |file|
puts file.read
end
elsif number == 2
puts "There are two people in the book."
File.open("book.txt","r") do |file|
puts file.read
end
elsif number >= 3
puts "There are some entries in the book."
File.open("book.txt","r") do |file|
puts file.read
end
end
end
,
要获取文件中的行数,您需要读取它。如果可能的话,您希望避免多次读取文件。
假设文件不是太大,可以使用IO::readlines 将其塞入数组:
arr = File.readlines("book.txt")
puts case arr.size
when 0
"There are no people in the book."
when 1
"There is one person in the book"
when 2
"There are two people in the book"
else
"There are some entries in the book"
end
puts arr
或者,您可以使用IO::read 将其塞入一个字符串:
str = File.read("book.txt")
puts case str.count("\n")
when 0
"There are no people in the book."
when 1
"There is one person in the book"
when 2
"There are two people in the book"
else
"There are some entries in the book"
end
puts str
如果文件太大,您一次只能读取一行,则可以使用IO::foreach。但是,这确实需要两次通过文件。
puts case File.foreach("book.txt").count
when 0
"There are no people in the book."
when 1
"There is one person in the book"
when 2
"There are two people in the book"
else
"There are some entries in the book"
end
File.foreach("book.txt") { |line| puts line }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。