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

在值不一致的情况下,通过map do分配ruby散列

  •  0
  • lilHar  · 技术社区  · 7 年前

    我有一张地图,我必须在使用前组装好。。。

    mailList = Customers.map do |customer|
    {
      :username => customer.name,
      :email => customer.email,
      :last_ip_v4 => customer.ipv4,
      :last_ip_v6 => customer.ipv6
    }
    end
    

    这适用于许多测试用户,但并非所有用户都有最后一个ipv4和最后一个ipv6。如果没有,ruby会出错,但我宁愿它只分配一个nil。我该怎么做?

    0 回复  |  直到 6 年前
        1
  •  1
  •   deepakumar m    6 年前

    mailList = Customers.map do |customer|
    

    将正常工作(可能是因为使用了错误的约定),然后尝试检查ipv4和ipv6的nil情况,并将列表构造为,

        mailList = construct_list Customers
        def construct_list data
          list = []
          hash ={}
          data.map do |customer|
            hash[:username] = customer.name
            hash[:email] = customer.email
            customer.ipv4.nil? ? hash[:last_ip_v4] = nil : hash[:last_ip_v4] = customer.ipv4
            customer.ipv6.nil? ? hash[:last_ip_v6] = nil : hash[:last_ip_v6] = customer.ipv6
            list << hash
          end
          list
        end
    

    虽然这可能不是最好的,但它会帮助你一段时间。

        2
  •  2
  •   demir    7 年前

    即使ipv4和ipv6为零,也不应该抛出错误。我认为这里的语法不正确或者 Customers 是零。试试这个方法:

    mailList = Customer.all.map do |customer|
      {
        username: customer.name,
        email: customer.email,
        last_ip_v4: customer.ipv4,
        last_ip_v6: customer.ipv6
      }
    end