有条件的地图

Map with conditions

如何使用 #map 隐藏 nil 的属性?

条件在块内不起作用,所以我尝试了这个:

account_info = some_db_request
account_info.fields.map do |field|
                    {
                        id: field.id,
                        hidden: field.hidden
                        size: field.size
                    }
account_info
=> "{\"email\":\"admin@test.com\",\"name\":\"admin@test.com\",\"roles\":[\"admin\",\"user\"],\"fields\":[{:id=>3, :hidden=>"",size=>80},{:id=>3, :hidden=>"true",size=>80}],\"redirect_to\":[]}"
then I convert output in json

我预计:

"fields": [
        {
            "id": 3, # if hidden = ''
            "size": 90
        },
        {
            "id": 4,
            "hidden": "true", if hidden = 'true'
            "size": 190
        }]

但是得到了:

"fields": [
        {
            "id": 3,
            "hidden" = ''
            "size": 90
        },
        {
            "id": 4,
            "hidden": "true" if hidden = 'true'
            "size": 190
        }]

如何获得预期的输出?

一个快速而肮脏的修复方法是在以下之后压缩哈希:

account_info.fields.map do |field|
  {
    id: field.id,
    hidden: field.hidden
    size: field.size
  }.compact!
end

account_info.fields.map do |field|
  {
    id: field.id,
    hidden: field.hidden
    size: field.size
  }.reject{|k,v| v.nil?}
end

或者最后没有首先分配任何 nil 值:

account_info.fields.map do |field|
  h = Hash.new
  h[:id] = field.id if !field.id.nil?
  h[:hidden] = field.hidden if !field.hidden.nil?
  h[:size] = field.size if !field.size.nil?
  h
end