Complex mapping of array to object in Ruby

我与影子孤独终老i 提交于 2020-01-16 06:40:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!