⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 08 - picking a random line from a file.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
module Enumerable  def random_line    selected = nil    each_with_index { |line, lineno| selected = line if rand < 1.0/lineno }        return selected.chomp if selected  endend#Create a file with 1000 linesopen('random_line_test', 'w') do |f|   1000.times { |i| f.puts "Line #{i}" }end#Pick random lines from the file.f = open('random_line_test')f.random_line                                    # => "Line 520"f.random_line                                    # => nilf.rewindf.random_line                                    # => "Line 727"#---File.open('random_line_test') do |f|  l = f.readlines  l[rand(l.size)].chompend# => "Line 708"#---$ ruby -e 'rand < 1.0/$. and line = $_ while gets; puts line.chomp'#---

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -