如何在Ruby中定义Hash之前使用Hash

时间:2014-04-23 23:42:19

标签: ruby hash

我有一个Ruby脚本,其中包含超过300个关联的非常长的Hash。 脚本如下所示:

#!/usr/bin/env ruby

Array_A = []
myHash = {
                "x1" => "2",
                "x2" => "0",
                "x3" => "1",
                .
                .
                .
                "X350" => "1"
                }

myHash.keys.each do |z|
    Array_A << "This is key " + z
end

puts myHash.values.join("|")                            
puts Array_A.join("|") 

但是由于Hash非常大,出于阅读目的,我想首先将Hash放在脚本的末尾,然后先放置each循环和puts命令,这样的事情就像这样:

Array_A = []

myHash.keys.each do |z|
    Array_A << "This is key " + z
end

puts myHash.values.join("|")                            
puts Array_A.join("|") 

myHash = {
                "x1" => "2",
                "x2" => "0",
                "x3" => "1",
                .
                .
                .
                "X350" => "1"
                }

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:2)

这有点奇怪,但这基本上就是DATA的用途。问题是,它是一个包含__END__之后部分内容的文件,所以你需要从那里转到哈希。如下所示:

Array_A = []

myHash = eval DATA.read    

myHash.keys.each do |z|
    Array_A << "This is key " + z
end

puts myHash.values.join("|")                            
puts Array_A.join("|") 

__END__
{ 
  "x1" => "2",
  "x2" => "0",
  "x3" => "1",
  …
  "X350" => "1"
}