在Ruby中读取文件的第一行 [英] Reading the first line of a file in Ruby

查看:171
本文介绍了在Ruby中读取文件的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以最快,最简单,最习惯的方式使用Ruby来读取文件的第一行。什么是最好的方法?特别是:我想读取我的最新Capistrano部署的Rails目录中的REVISION文件的git提交UUID,然后输出到我的标签,这会让我看到什么版本部署到我的服务器,如果有一个完全不同的和更好的方式来做到这一点,请让我知道。)

解决方案

File.open('somefile.txt'){| f | f.readline}
#或者在Ruby 1.8.7及以上版本中:#
File.open('somefile.txt',&:readline)


I want to read only the first line of a file using Ruby in the fastest, simplest, most idiomatic way possible. What's the best approach?

(Specifically: I want to read the git commit UUID out of the REVISION file in my latest Capistrano-deployed Rails directory, and then output that to my tag. This will let me see at an http-glance what version is deployed to my server. If there's an entirely different & better way to do this, please let me know.)

解决方案

This will read exactly one line and ensure that the file is properly closed immediately after.

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

这篇关于在Ruby中读取文件的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆