0

如何摆脱这种重复if conditional

def set_caption(result)
  if result.respond_to?(:app_name)
    content_tag(:div, result.type_name, class: 'type-name') + 
      content_tag(:div, result.app_name, class: 'app-name')
  else
    content_tag(:div, result.type_name, class: 'type-name')
  end
end
4

2 回答 2

1

这对你有用吗?

def set_caption(result)
  rv = content_tag(:div, result.type_name, class: 'type-name')
  if result.respond_to?(:app_name)
    rv += content_tag(:div, result.app_name, class: 'app-name')
  end
  rv
end
于 2013-02-01T22:36:32.510 回答
-2
def set_caption(result)
  [:type_name, *(:app_name if result.respond_to?(:app_name))]
  .map{|name| content_tag(:div, result.send(name), class: name.hyphenize)}
  .inject(:+)
end

或者,假设这result.respond_to?(:type_name)总是正确的:

def set_caption(result)
  [:type_name, :app_name]
  .map{|name| if result.respond_to?(name)
    content_tag(:div, result.send(name), class: name.hyphenize)
  end}.compact.inject(:+)
end
于 2013-02-01T22:48:07.683 回答