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

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

    I saw some people asking how to handle this for nil cases.

    The trick is to convert it to string. All nils converted to string becomes a empty string, all empty cases continue being empty.

    nil.to_s.empty?
    "".to_s.empty?
    

    both will return true

提交回复
热议问题