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

后端 未结 7 2552
名媛妹妹
名媛妹妹 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:30

    Assuming that "process empty array" leaves it empty after processing, you can leave out the else:

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

    or in one line:

    array.empty? ? process_empty_array : array.each { |el| process_el } 
    

提交回复
热议问题