【问题标题】:Assigning a ruby hash by map do where values don't consistantly exist在值不一致的情况下,通过 map 分配 ruby​​ 哈希
【发布时间】:2019-09-09 22:14:15
【问题描述】:

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

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

这适用于许多测试用户,但并非所有用户都有最后一个 ipv4 和一个最后一个 ipv6。当他们不这样做时,红宝石会出错,但我宁愿它只是分配一个零。我该怎么做?

【问题讨论】:

  • 您的代码块丢失了end,但我假设您在本地拥有它,代码似乎没问题,但您能与我们分享您的执行和错误输出吗?
  • 你能显示错误吗?另外,你从哪里得到Customers
  • @MarkMerritt /bundle/gems/activemodel-4.1.16/lib/active_model/attribute_methods.rb:435:in `method_missing' 是我得到的错误。而且我在该代码之前和之后都有输出,所以我知道这就是它的问题所在。
  • @Coco 我最后加了。是的,它在我的本地。
  • 什么是Customers?它是对象或类名的数组吗?

标签: ruby-on-rails arrays ruby hash


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果你确定这条线,

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 2011-01-15
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      相关资源
      最近更新 更多