Ruby best practice : if not empty each do else in one operator

后端 未结 7 2513
名媛妹妹
名媛妹妹 2021-02-18 16:04

1.I can\'t find an elegant way to write this code:

if array.empty?
  # process empty array
else
  array.each do |el|
    # process el
  end
end

7条回答
  •  灰色年华
    2021-02-18 16:10

    The cleanest way I've seen this done in HAML (not plain Ruby) is something like:

    - array.each do |item|
        %li
            = item.name
    - if array.empty?
        %li.empty
            Nothing here.
    

    As mentioned by other answers, there is no need for the else clause because that's already implied in the other logic.

    Even if you could do the each-else in one clean line, you wouldn't be able to achieve the markup you're trying to achieve (

    if array.empty?,

      if array.present?). Besides, the HAML you show in your question is the best way to tell the story behind your code, which means it will be more readable and maintainable to other developers, so I don't know why you would want to refactor into something more cryptic.

提交回复
热议问题