QWD666
QWD666

Reputation: 129

Map with conditions

How can I use #map to hide an attribute if it's nil?

Conditions aren't working inside a block, so I tried this:

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

I expected:

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

But got:

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

How can I get the expected output?

Upvotes: 0

Views: 75

Answers (1)

Mark
Mark

Reputation: 6455

A quick and dirty fix is to just compact the hash after:

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

or

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

Or finally without assigning any nil values in the first place:

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

Upvotes: 3

Related Questions