如果属性nil
,如何使用#map
隐藏属性?
条件在块内不起作用,所以我尝试了这个:
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