结合从Ruby中相同哈希中解析的数据

时间:2016-03-17 17:31:51

标签: ruby hash

我试图合并我从单个哈希过滤掉的大型数据集。我尝试过各种各样的事情,例如合并,但似乎无法将数据与我想象的方式结合起来。以下是我尝试合并的内容:

puts '','=========GET INFO'
print_data = targetprocess.comments_with_ids #get the hash
puts print_data #show the hash for verification

puts '','=========GET IDs'
story_ids = print_data['Comments']['Comment'].map {|entry| entry['General']} #filter for story ids and story name
puts story_ids

puts '','=========GET COMMENTS'
comment_description = print_data['Comments']['Comment'].map {|words| words['Description']} #get all comments, these are in the same order as the story ids
puts comment_description

最终我希望它看起来像是:

story_id 1 + comment_description 1

story_id 2 + comment_description 2

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我最终意识到哈希有一些我可以使用的其他嵌套结构。在这个例子中,我使用嵌套哈希,然后将其存储为数组(我最终需要将其用于其他工作),然后输出。

puts '','=========GET INFO'
print_data = targetprocess.comments_with_ids #get the hash
puts print_data #show the hash for verification
puts '=========COMPLETE', ''

#=========HASH OF USEFUL DATA
results = {}
print_data['Comments']['Comment'].each{|entry|
  results[entry['Id'].chomp] = {:parent_id => entry['General']['Id'].chomp, :description => entry['Description'].chomp}}

#=========STORE HASH AS AN ARRAY
csv_array = []
results.each{|key,value|
  csv_array << [key, value[:parent_id], value[:description]]
  #=======FRIENDLY OUTPUT
  puts "Story_Id #{value[:parent_id]}, Comment_Id #{key}, Comment #{value[:description]}"}