在 Ruby 中从数组数组创建映射

问题描述 投票:0回答:1

我正在尝试用 Ruby 编写一个函数,它可以接受数组数组中的 a ,并将其转换为哈希值。这将用于模拟语法并生成随机句子。生成的映射将有助于生成当前语法规则可用的所有句子组合。

要输入的数组的数组格式如下:

[  
["<start>", "The   <object>   <verb>   tonight."],   
["<object>", "waves", "big    yellow       flowers", "slugs"],   
["<verb>", "sigh <adverb>", "portend like <object>", "die <adverb>"],   
["<adverb>", "warily", "grumpily"]  
]

将 this 传递给函数并映射它后,结果应该是这样的:

{
"<start>"=>[ ["The", "<object>", "<verb>", "tonight."] ], 
"<object>"=>[ ["waves"] , ["big", "yellow", "flowers"] , ["slugs"] ], 
"<verb>"=>[ ["sigh", "<adverb>"] , ["portend", "like", "<object>"] , ["die", "<adverb>"] ], 
"<adverb>"=>[ ["warily"] , ["grumpily"] ]
}

对于每个非终结符,它应该将其相应的产生式映射到它。例如,将包含“warly”和“grumpily”,因为这两个是对应于非终结符的产生式。

我该如何实现这一目标?我有点不知道从哪里开始。

ruby
1个回答
2
投票

试试这个:

arr = [ ["<start>", "The   <object>   <verb>   tonight."],   
        ["<object>", "waves", "big    yellow       flowers", "slugs"],   
        ["<verb>", "sigh <adverb>", "portend like <object>", "die <adverb>"],   
        ["<adverb>", "warily", "grumpily"] ]

arr.map { |ar| [ar.shift, ar.map { |str| str.split }] }.to_h
#=>
#{ "<start>"  => [["The", "<object>", "<verb>", "tonight."]],
#  "<object>" => [["waves"], ["big", "yellow", "flowers"], ["slugs"]],
#  "<verb>"   => [["sigh", "<adverb>"], ["portend", "like", "<object>"], ["die", "<adverb>"]],
#  "<adverb>" => [["warily"], ["grumpily"]] }

ar.shift
取每个子数组的第一个元素。与
ar.map
一起使用的块将剩余元素(在空白处)拆分为数组。最后
to_h
将结果数组转换为哈希值。

© www.soinside.com 2019 - 2024. All rights reserved.