问题
I have an array of strings:
["username", "String", "password", "String"]
And I want to convert this array to a list of Field objects:
class Field
attr_reader :name, :type
def initialize(name, type)
@name = name
@type = type
end
end
So I need to map "username", "String" => Field.new("username", "String") and so on. The length of the array will always be a multiple of two.
Does anyone know if this is possible using a map style method call?
回答1:
1.8.6:
require 'enumerator'
result = []
arr = ["username", "String", "password", "String"]
arr.each_slice(2) {|name, type| result << Field.new(name, type) }
Or Magnar's solution which is a bit shorter.
For 1.8.7+ you can do:
arr.each_slice(2).map {|name, type| Field.new(name, type) }
回答2:
A bracketed Hash call does exactly what you need. Given
a = ["username", "String", "password", "String"]
Then:
fields = Hash[*a].map { |name, type| Field.new name, type }
回答3:
Take a look at each_slice. It should do what you need.
来源:https://stackoverflow.com/questions/1287648/complex-mapping-of-array-to-object-in-ruby