散列值为Hash或Array Ruby

时间:2015-03-02 00:45:41

标签: ruby hash

我正在尝试对某些记录进行分组,但很可能是效率低下。需要帮助 -

首先,我从处理过的一堆文件中收集了以下一组数据 -       
BookA - section1,section2
      BookB - 第2节,第4节

我使用了hh = Hash.new {| h,k | h [k] = {}}并将其存储为 -

hh[BookA][section1] = BookA
hh[BookA][section2] = BookA
hh[BookB][section2] = BookB
hh[BookB][section4] = BookB

但是我需要打印所有这些如下 -     
第1节 - BookA     
第2节 - BookA     
第2节 - BookB     
第4节 - BookB

有关如何做到这一点的任何建议......

所以我创造了 h = Hash.new {| h,k | H [K] = []}
section_hash = Hash.new([])
迭代 -
h.each do | k,v |
v.each do | s |
put"#{s} - #{k}"
fh [s]<< ķ
结束
结束
放fh
它正确打印所有内容但是fh是零,任何想法都是错误的.... 输出来自puts命令
s1 - b1
s2 - b1
s2 - b2

1 个答案:

答案 0 :(得分:0)

我可以通过将此部分用作哈希键来实现,如下所示:

# so this will create a new empty array for any keys we add
section_hash = Hash.new([])

# you can grab out the lines of the file or use each to do it line by line.
book_lines = File.readlines("my_file.txt")

# now go through each of these and add the data into the hash
book_lines.each do |line|

  # convert each line to a key/value pair
  # eg "BookA - section1, section2"
  # {"BookA" => ["section1", "secton2"]}
  book, sections = line.split(" - ")
  sections = sections.split(', ')    

  # and hash away these values
  sections.each do |section|
     section_hash[section] << book
  end
end

然后你可以打印:

section_hash.each do |section, books|
  # you may choose to uniq (in case of double ups)
  books.uniq.each do |book|
    puts "#{section} - #{book}"
  end
end