Ruby best practice : if not empty each do else in

2020-06-30 12:09发布

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

I'd like to have one loop, without writing array twice. I read this, but there is no solution good enough.


2. I am actually in an HAML template. Same question.

- if array.empty?
  %p No result
- else
  %ul
  - array.each do |el|
    %li el

7条回答
萌系小妹纸
2楼-- · 2020-06-30 12:37

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
查看更多
登录 后发表回答