如果空的话怎么不传递参数?

时间:2012-09-12 06:02:36

标签: ruby

我将ruby从1.8.x升级到1.9.3不确定pony gem是否在该过程中升级但重点是我使用此代码发送电子邮件

Pony.mail(
    :to => to, 
    :from => from,
    :subject => subject, 
    :body => Nokogiri::HTML(body_with_footer).text, 
    :html_body =>  body_with_footer, #.gsub("\n","<BR>"),
    :attachments => attachment_to_send,
    :via => :smtp, 
    :via_options => {
            :address     => $smtp,
            :port     => $smtp_port,
            :enable_starttls_auto => false
    }
)

attachment_to_send应该是要附加的文件的哈希值。当哈希为空时,没有发送附件。现在我得到一个小马错误抱怨哈希是“”​​。

所以我引入了一个if条件attachment_to_send==""所以我称小马有或没有附件。

有没有办法管理它?所以我只有一个代码,我称之为小马?

2 个答案:

答案 0 :(得分:1)

通过以下方式检查空状态

来准备附件阵列
 tmp_hash = {:to => to, 
             :from => from,
             :subject => subject, 
             :body => Nokogiri::HTML(body_with_footer).text, 
             :html_body =>  body_with_footer, #.gsub("\n","<BR>"),
             :via => :smtp, 
             :via_options => {
                            :address     => $smtp,
                            :port     => $smtp_port,
                            :enable_starttls_auto => false
                             }
             } 

tmp_hash[:attachments] => attachment_to_send
tmp_hash[:attachments] => nil if attachment_to_send.empty?

或 直接,

 tmp_hash[:attachments] =>  attachment_to_send if not attachment_to_send.empty?

然后

Pony.mail( tmp_hash)

应该有效

答案 1 :(得分:1)

使用三元运算符attachment_to_send.empty? ? nil : attachment_to_send处理

      details = {
            :to => to, 
            :from => from,
            :subject => subject, 
            :body => Nokogiri::HTML(body_with_footer).text, 
            :html_body =>  body_with_footer, #.gsub("\n","<BR>"),
            :attachments => attachment_to_send.empty? ? nil : attachment_to_send ,
            :via => :smtp, 
            :via_options => {
                    :address     => $smtp,
                    :port     => $smtp_port,
                    :enable_starttls_auto => false
            }


Pony.mail(details)