[英]Draw random number from text file
所以我有這段代碼將一些數字放入文本文件中。
outFile = File.new("Demo.txt", "a+")
outFile.puts (1..5).map{ '%05d' % rand(00000..99999) }
outFile.close
puts File.read("Demo.txt")
而且我想知道是否可以提取已創建的隨機數之一。
我會做如下:
File.open("Demo.txt", "a+") do |file|
file.puts (1..5).map{ '%05d' % rand(00000..99999) }
end
# give you any random number from the file
puts File.readlines("Demo.txt").map(&:strip).sample
IO::readlines
將為您提供放置在文件"Demo.txt"
所有數字,作為一個Array
。 現在Array#sample
將選擇一個隨機元素 。
為什么我使用IO::open
? 同樣閱讀以下內容:
沒有關聯的塊,
IO.open
是::new
的同義詞。 如果給出了可選代碼塊,它將作為參數傳遞io,並且在該代碼塊終止時 IO對象將自動關閉 。 在這種情況下,::open
返回該塊的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.