Ruby中数组到对象的复杂映射

我有一个字符串数组:

["username", "String", "password", "String"] 

我想将此数组转换为Field对象列表:

 class Field attr_reader :name, :type def initialize(name, type) @name = name @type = type end end 

所以我需要映射“username”,“String”=> Field.new(“username”,“String”)等等。 数组的长度始终是2的倍数。

有没有人知道这是否可以使用地图样式方法调用?

1.8.6:

 require 'enumerator' result = [] arr = ["username", "String", "password", "String"] arr.each_slice(2) {|name, type| result << Field.new(name, type) } 

或者Magnar的解决方案有点短。

对于1.8.7+,您可以:

 arr.each_slice(2).map {|name, type| Field.new(name, type) } 

括号中的Hash调用完全符合您的需要。 特定

 a = ["username", "String", "password", "String"] 

然后:

 fields = Hash[*a].map { |name, type| Field.new name, type } 

看看each_slice 。 它应该做你需要的。

Interesting Posts