ruby怎么读取文件的列数

Python010

ruby怎么读取文件的列数,第1张

简单说一下吧,假设你有一个名为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,大功告成。

不建议使用print函数。使用puts函数即可:

class HelloWorld

def HelloWorld.hello(name = "Ruby")

  puts "Hello,world.I am #{name}."

end

end

HelloWorld.hello("Jone")

HelloWorld.hello