如果不为null,则将哈希添加到哈希数组中?

时间:2017-08-24 18:50:43

标签: ruby-on-rails arrays ruby hash

我有一个方法,它接受许多参数,包括附件,我希望只在非空时包含在哈希中。有没有办法写这个没有为两种情况构建哈希? 我当前的哈希数组看起来像这样

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}]

2 个答案:

答案 0 :(得分:2)

是的,确定你可以:

messagehash[0][:attachment] = attachment_hash if attachment

答案 1 :(得分:1)

首先,看起来你有一个只有一个元素的数组,一个哈希。那是你想要的,还是哈希?

例如,你有什么:

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

应该有效。但我认为你真的只想添加一个项目到一个哈希(不是你上面提到的哈希数组),所以像这样的东西会起作用 H:

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