[英]adding a hash to an array of hash if not null?
我有一個方法,它接受許多參數,包括附件,僅當不為null時,我才希望將其包括在哈希中。 有沒有一種方法可以編寫這兩種情況而無需構造哈希值? 我當前的哈希數組看起來像這樣
messagehash = [{ :from => fromhash,
:content => contenthash,
:to => tohash,
:sentDate => datetime.to_i,
:isPrivate => false,
:sourceInboxes => [sender.email],
:subject => subject}]
如果滿足條件,我可以將哈希添加到列表中嗎? 像這樣的東西
if attachment
messagehash[0].attachment = attachment_hash
end
這樣它可以像這樣結束
messagehash = [{ :from => fromhash,
:content => contenthash,
:to => tohash,
:sentDate => datetime.to_i,
:isPrivate => false,
:sourceInboxes => [sender.email],
:subject => subject,
:attachment => attachment_hash}]
是的,請確保您可以:
messagehash[0][:attachment] = attachment_hash if attachment
首先,似乎您的數組只有一個元素,即哈希。 這就是您想要的,還是只是一個哈希?
例如,您擁有:
messagehash = [{ :from => fromhash,
:content => contenthash,
:to => tohash,
:sentDate => datetime.to_i,
:isPrivate => false,
:sourceInboxes => [sender.email],
:subject => subject}]
如果像這樣省略[],則需要messagehash[0][:from]
來訪問fromhash
僅messagehash[:from]
。
messagehash = { :from => fromhash,
:content => contenthash,
:to => tohash,
:sentDate => datetime.to_i,
:isPrivate => false,
:sourceInboxes => [sender.email],
:subject => subject}
如果您確實打算將散列作為數組的第一個元素,則類似於:
messagehash[0][:attachment] = attachment_hash if attachment_hash
應該管用。 但是我認為您真的只想將一個項目添加到哈希中(而不是您上面提到的哈希數組),所以類似的事情將起作用:
messagehash = { :from => fromhash,
:content => contenthash,
:to => tohash,
:sentDate => datetime.to_i,
:isPrivate => false,
:sourceInboxes => [sender.email],
:subject => subject}
messagehash[:attachment] = attachment_hash if attachment_hash
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.