将数组转换为Hash Ruby

时间:2017-10-31 20:17:36

标签: ruby

我有一个包含以下内容的数组:

[["< start >", "The   < object >   < verb >   tonight."], 
 ["< object >", "waves", "big    yellow       flowers", "slugs"]]

我想创建一个返回的Hash

{"< start >"=>[["The", "< object >", "< verb >", "tonight."]], 
 "< object >"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]]}

我想做一些匹配的key.to_s.match(/&lt;?&gt; /),但我不知道如何实现.complete noob

3 个答案:

答案 0 :(得分:1)

arr = [["< start >", "The   < object >   < verb >   tonight."], 
       ["< object >", "waves", "big    yellow       flowers", "slugs"]]

arr.each_with_object({}) { |(first, *rest),h|
  h[first] = rest.map { |s| s.scan(/\< \S+ \>|\S+/) } }
  #=> {"< start > "=>[["The", "< object >", "< verb >", "tonight."]],
  #    "< object >"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]]}.

答案 1 :(得分:0)

您需要稍微更改输入,但您可能需要Hash#[]docs)。

示例:

arry = [["key1", "val1"], ["key2", "val2"]]
Hash[arry]
 # => {"key1"=>"val1", "key2"=>"val2"} 

因此,您需要将数组按到一组键和值的数组中。

input = [
  ["< start >", "The   < object >   < verb >   tonight."],
  ["< object >", "waves", "big    yellow       flowers", "slugs"]
]

massaged_input = input.map{|arry| [arry.slice!(0), arry.join.squeeze(" ")] }
 # => [["< start >", "The < object > < verb > tonight."], ["< object >", "wavesbig yellow flowersslugs"]]    

Hash[massaged_input]
 # => {"< start >"=>"The < object > < verb > tonight.", "< object >"=>"wavesbig yellow flowersslugs"} 

答案 2 :(得分:0)

这就是我对这个具体例子的看法

a = [["< start >", "The   < object >   < verb >   tonight."], 
 ["< object >", "waves", "big    yellow       flowers", "slugs"]]

a.each_with_object({}) { |(k,*v), obj| obj[k] = v.map { |a| a.scan(/<\s\w+\s>|\w+/) } } 
#=> {"< start >"=>[["The", "< object >", "< verb >", "tonight"]], 
#    "< object >"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]]}

这只是使用一个简单的正则表达式将字符串解析为请求的格式。

Code Example

正则表达式:/<\s\w+\s>|\w+/

  • 匹配<\s\w+\s>
    • <(字面意思)
    • \s空间
    • \w+一个或多个单词字符(字母,数字,下划线)
    • \s空间
    • >(字面意思)
  • |
  • 匹配\w+一个或多个单词字符(字母,数字,下划线)

Regex Example