如何读取哈希数组作为input.txt文件,以便在ruby中进行排序

laik7k3q  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(274)

下面是我保存到input.txt文件的哈希数组

arr_hash = [{"Name"=>"Aku","Email"="hello@gmail.com,"place"=>"abc"},
         {"Email"=>"xyz@gmail.com.com","place="India","Name"=>"Rocky"}
         {"place"=>"India","Email"=>"abc@gmail.com","Name"=>"Rocky"}]

下面是一段代码,我试图从文本文件中读取哈希数组进行排序(main.rb)

file = File.open("input.txt","r+")
sorted = file.map{|h| h.values_at(:Name, :place, :Email)}.sort
puts sorted

这是生成新文件以显示输出的代码

output_file = File.open("outputfile.txt","w" )
output_file << sorted
output_file.close

当我试图读取input.txt文件以对其进行相应的排序时,我得到了下面的错误

undefined method `values_at' for #<String:0x000055fac2499158> (NoMethodError)
vptzau2j

vptzau2j1#

在我看来,文本文件不是一个合适的选择。相反,为什么不使用json呢?
您可以这样定义您的文件:

{
  "1": {
    "Name": "Aku",
    "Email": "hello@gmail.com",
    "place": "abc"
  },
  "2": {
    "Email": "xyz@gmail.com.com",
    "place": "India",
    "Name": "Rocky"
  },
  "3": {
    "place": "India",
    "Email": "abc@gmail.com",
    "Name": "Rocky"
  }
}

将其导入ruby,如下所示:

require 'json'

file = File.read 'input.json'
data = JSON.parse file

data.class 

# => Hash

data.first

# => ["1", {"Name"=>"Aku", "Email"=>"hello@gmail.com", "place"=>"abc"}]

data.each_value { |value| puts value['Name'] }

# => Aku

# => Rocky

# => Rocky

将散列转储为json非常容易:

my_hash = {
  "Name"=>"Aku",
  "Email"=>"hello@gmail.com",
  "place"=>"abc"
}

File.write('output.json', JSON.dump(my_hash))

相关问题