将以分隔符分隔的字符串数组转换为哈希表的Ruby代码

3

我有一个数组

["bob:12 elm st", "sally:100 digital ave", "tom:2324 elmhurst st"] 

我需要将

转换为


{"bob" => "12 elm st", "sally" => "100 digital ave", "tom" => "2324 elmhurst st"}.

我知道我能做到。
array.each do |e|
  k = e.split(":").first
  v = e.split(":").last
  hash[k] = v
end

有没有更优雅的方法来完成这个任务?

2个回答

7

我相信Ruby 2.1版本具有.to_h方法。

因此,

array.map { |i| i.split ':' }.to_h 

会起作用。


7

Hash[] 会从数组构建哈希表。

Hash[array.map {|el| el.split ':'}]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接