这种红宝石(铁轨)方法可以整理吗?

时间:2011-12-18 12:28:55

标签: ruby-on-rails ruby

我对ruby很新(并且正在使用Rails),并且想知道是否可以整理以下方法。在它当前状态下它确实有效,但是我觉得有一种更好的编写方式,并希望了解更多有关语法的知识。

def fullAddress
  full = self.address1 + "</br>"
  if self.address2.blank?
  else
    full = full + self.address2  + "</br>"
  end
  if self.address3.blank?
  else
    full = full + self.address3  + "</br>"
  end
  full = full + self.posttown + "</br>" + self.postcode
end

每个'self'都有address1,posttown和postcode,但是address2和address3是可选的,只有当它们存在时才应添加到fullAddress(即nil或空白)。

这个问题可能不太适合SO,但是我已经遇到过这种类型的帮助方法了,我相信我能以更好的方式实现它。

5 个答案:

答案 0 :(得分:12)

def full_address
  [address1, address2, address3, posttown, postcode].reject{|l| l.blank?}.join('</br>')
end

答案 1 :(得分:5)

我的看法:

def fullAddress
  full = [address1]
  full << address2 unless address2.blank?
  full << address3 unless address3.blank?
  full << posttown << postcode
  full.join "</br>"
end

self隐含在方法调用中,并且有点玩弄数组。

答案 2 :(得分:1)

def fullAddress
  full = address1 + "<br>"
  full += address2 + "<br>" unless address2.blank?
  full += address3 + "<br>" unless address3.blank?
  full += posttown + "<br>" + postcode
end

答案 3 :(得分:1)

与您的代码完全相同

def full_adress
  ([address1] +
   [address2, address3].reject(&:blank?) +
   [posttown, postcode]
  ).join("<br/>")
end

答案 4 :(得分:0)

这是另一种解决方案:

def full_address
  [address1,
   address2,
   address3,
   posttown,
   postcode].inject("") do |full_addr, line|
     full_addr << line + '<br/>' unless line.blank?
     full_addr
   end.chomp('</br>')
end

它只需要一个数组,并立即开始构造字符串。它应该适用于短字符串(完整地址是短字符串)。