簡體   English   中英

在Ruby中讀取文件的第一行

[英]Reading the first line of a file in Ruby

我想以最快,最簡單,最慣用的方式使用Ruby 讀取文件的第一行。 什么是最好的方法?

(具體來說:我想從我最新的Capistrano部署的Rails目錄中的REVISION文件中讀取git commit UUID,然后將其輸出到我的標簽。這樣我就可以在http瀏覽器中看到部署到我服務器的版本如果有完全不同的更好的方法,請告訴我。)

這將只讀取一行並確保文件在之后立即正確關閉。

strVar = File.open('somefile.txt') {|f| f.readline}
# or, in Ruby 1.8.7 and above: #
strVar = File.open('somefile.txt', &:readline)
puts strVar

這是一個簡潔的慣用方法,可以正確打開文件進行閱讀,然后關閉它。

File.open('path.txt', &:gets)

如果您想要一個空文件導致異常,請使用它。

File.open('path.txt', &:readline)

此外,這是一個快速和臟的頭部實現,可以用於您的目的,在許多其他情況下,您想要閱讀更多的行。

# Reads a set number of lines from the top.
# Usage: File.head('path.txt')
class File
  def self.head(path, n = 1)
     open(path) do |f|
        lines = []
        n.times do
          line = f.gets || break
          lines << line
        end
        lines
     end
  end
end

你可以試試這個:

File.foreach('path_to_file').first

如何讀取ruby文件中的第一行:

commit_hash = File.open("filename.txt").first

或者,您可以從應用程序內部執行git-log:

commit_hash = `git log -1 --pretty=format:"%H"`

%H告訴格式打印完整的提交哈希。 還有一些模塊允許您以更加紅寶石的方式從Rails應用程序內部訪問本地git repo,盡管我從未使用它們。

first_line = open("filename").gets

我認為調查git --pretty選項的jkupferman建議最有意義,但是另一種方法是head命令,例如

ruby -e 'puts `head -n 1 filename`'  #(backtick before `head` and after `filename`)
first_line = File.readlines('file_path').first.chomp

改進@Chuck發布的答案,我認為值得指出的是,如果您正在閱讀的文件為空,則會拋出EOFError異常。 捕獲並忽略異常:

def readit(filename)
 text = ""
 begin
   text = File.open(filename, &:readline)
 rescue EOFError
 end
 text
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM