ruby怎么安装yml

Python012

ruby怎么安装yml,第1张

首先用一个在Rails开发中一定会遇到的YAML文件——database.yml——作为示例。在你创建一个Rails工程后,Rails会自动给你创建一个这样的文件,它的路径是config/database.yml:

# MySQL (default setup). Versions 4.1 and 5.0 are recommended.

# 此处省略一些注释。

development:

adapter: mysql

database: demo_development

username: root

password:

host: localhost

# Warning: The database defined as 'test' will be erased and

# re-generated from your development database when you run 'rake'.

# Do not set this db to the same as development or production.

test:

adapter: mysql

database: demo_test

username: root

password:

host: localhost

production:

adapter: mysql

database: demo_production

username: root

password:

host: localhost

简单说一下吧,假设你有一个名为example.txt的文件,里面的内容如下:

bbb ccc 123

ddd aaa 456

abc efg 789

695 aaa uwi

注意,这里我举的例子每一列是用空格分隔的。

用ruby读取的代码如下:

f = File.open("example.txt")

f.each_line { |line| p line.split.first if line =~ /\saaa\s/ }

运行结果 #=>"ddd"

"695"

OK,大功告成。

ruby读取指定的行,可以使用readlines将整个文件的内容读取到一个数组中,再获得指定行的数据

arr = io.readlines

p arr[9] # 读出第10行的数据