在Ruby中读取文件的第一行

Cra*_*ker 59 ruby git file-io capistrano ruby-on-rails

我想以最快,最简单,最惯用的方式使用Ruby 读取文件的第一行.什么是最好的方法?

(具体来说:我想从我最新的Capistrano部署的Rails目录中的REVISION文件中读取git commit UUID,然后将其输出到我的标签.这将让我看到http浏览器部署到我的服务器的版本如果有完全不同的更好的方法,请告诉我.)

Chu*_*uck 105

这将只读取一行并确保文件在之后立即正确关闭.

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


Bla*_*lor 17

这是一个简洁的惯用方法,可以正确打开文件进行阅读,然后关闭它.

File.open('path.txt', &:gets)
Run Code Online (Sandbox Code Playgroud)

如果您想要一个空文件导致异常,请使用它.

File.open('path.txt', &:readline)
Run Code Online (Sandbox Code Playgroud)

此外,这是一个快速和脏的头部实现,可以用于您的目的,在许多其他情况下,您想要阅读更多的行.

# 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
Run Code Online (Sandbox Code Playgroud)


Vin*_*ent 7

你可以试试这个:

File.foreach('path_to_file').first
Run Code Online (Sandbox Code Playgroud)

  • @klochner:你的Ruby已经老了.这在1.8.7及以上版本中工作正常. (3认同)

小智 6

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

commit_hash = File.open("filename.txt").first
Run Code Online (Sandbox Code Playgroud)

或者,您可以从应用程序内部执行git-log:

commit_hash = `git log -1 --pretty=format:"%H"`
Run Code Online (Sandbox Code Playgroud)

%H告诉格式打印完整的提交哈希.还有一些模块允许您以更加红宝石的方式从Rails应用程序内部访问本地git repo,尽管我从未使用它们.


Jer*_*ten 5

first_line = open("filename").gets
Run Code Online (Sandbox Code Playgroud)