Lets say I have text file like this:
假设我有这样的文本文件:
1 2 3
4 5 6
7 8 9
...
I want to read it into data structure like this:
我想把它解读成这样的数据结构:
h[1] = { "a" => 1, "b" => 2, "c" => 3 }
h[2] = { "a" => 4, "b" => 5, "c" => 6 }
h[3] = { "a" => 7, "b" => 8, "c" => 9 }
At first it seems easy. I use:
起初看起来很容易。我使用:
lines=File.read(ARGV[0]).split("\n")
h=[]
lines.each ( |x| h <
And completely stuck at this point. How can I convert h to array of hashes?
完全停留在这一点上。如何将h转换为哈希数组?
4
lines = File.readlines(ARGV[0])
lines.map { |l| x = l.split(/\s/).map(&:to_i); { 'a' => x[0], 'b' => x[1], 'c' => x[2] } }
4
def parse(filename)
File.readlines(filename).map do |line|
Hash[('a'..'c').zip(line.split.map(&:to_i))]
end
end
parse(ARGV[0]) # => [{"a"=>1, "b"=>2, "c"=>3}, {"a"=>4, "b"=>5, "c"=>6}, {"a"=>7, "b"=>8, "c"=>9}]
1
There is a Gem you can use for this: smarter_csv
您可以使用Gem: smarter_csv
Put this in your Gemfile:
把这个放在你的Gemfile里:
gem 'smarter_csv', '1.0.5'
and then:
然后:
require 'smarter_csv'
result = SmarterCSV.process('/tmp/bla.csv',
{:col_sep => ' ',
:headers_in_file => false,
:user_provided_headers => ['a','b','c'],
:strings_as_keys => true
}
)
=> [{"a"=>1, "b"=>2, "c"=>3},
{"a"=>4, "b"=>5, "c"=>6},
{"a"=>7, "b"=>8, "c"=>9}]
result[0]
=> {"a"=>1, "b"=>2, "c"=>3}
See also: smarter_csv
README
参见:smarter_csv README
1
I'd use:
我使用:
require 'pp'
ary = []
DATA.each_line do |li|
ary <
Running that I get:
我得到的运行:
[{"a"=>"1", "b"=>"2", "c"=>"3"},
{"a"=>"4", "b"=>"5", "c"=>"6"},
{"a"=>"7", "b"=>"8", "c"=>"9"}]
Change ary
to h
if you want that to be your variable name.
如果你想让它成为你的变量名,就把ary改成h。
If you're reading from a file use File.foreach('file/to/read.txt')
instead of each_line
.
如果您正在读取一个文件,请使用file .foreach('file/to/read.txt')代替each_line。
0
My solution is not as elegant as Christian's:
我的解决方案不像克里斯汀的那么优雅:
base = ['a','b','c']
h=[]
i = 0 # traverses the a,b,c
j = 1 # traverses the lines of the hash h
File.open(ARGV[0]).each_line do |line|
arr = line.split(' ')
arr.each do |x|
if !h[j].nil?
h[j][base[i]] = x.to_i
else # first entry in the hash should be set like this:
h[j] = {base[i] => x.to_i}
end
i += 1;
end
i = 0
j += 1
end
p h[1]
p h[2]
p h[3]
output:
输出:
{"a"=>"1", "b"=>"2", "c"=>"3"}
{"a"=>"4", "b"=>"5", "c"=>"6"}
{"a"=>"7", "b"=>"8", "c"=>"9"}
I started from j = 1 since that's what the OP asked for, even though it would probably make more sense to start from zero.
我从j = 1开始因为这是OP要求的,即使从0开始更有意义。