代码之家  ›  专栏  ›  技术社区  ›  BefittingTheorem

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

  •  1
  • BefittingTheorem  · 技术社区  · 16 年前

    我有一组字符串:

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

    我想把这个数组转换成一个字段对象列表:

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

    因此,我需要映射“username”、“string”=>field.new(“username”、“string”)等。数组的长度将始终是2的倍数。

    有人知道使用map-style方法调用是否可行吗?

    3 回复  |  直到 16 年前
        1
  •  2
  •   sepp2k    16 年前

    1.8.6:

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

    或者麦格纳的解决方案,稍微短一点。

    对于1.8.7+,您可以执行以下操作:

    arr.each_slice(2).map {|name, type| Field.new(name, type) }
    
        2
  •  4
  •   Magnar    16 年前

    加括号的哈希调用完全满足您的需要。鉴于

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

    然后:

    fields = Hash[*a].map { |name, type| Field.new name, type }
    
        3
  •  2
  •   Matt Grande    16 年前

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

    推荐文章