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

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

    If array is empty, then it will not be iterated, so the each block does not need to be conditioned. Since the return value of each is the receiver, you can put the each block within the empty? condition.

    if (array.each do |el|
      # process el
    end).empty?
      # process empty array
    end
    
    0 讨论(0)
提交回复
热议问题