Return empty array (Ruby)

前端 未结 3 1088
天涯浪人
天涯浪人 2020-12-21 08:15

I am trying to create a condition statement in Ruby. If my array of various numbers is empty or nil, it should return an empty array otherwise it should sort the numbers. Th

3条回答
  •  情深已故
    2020-12-21 09:09

    To fix your code, change what you have to one of the following:

    num.nil? || num.empty? ? [] : num.sort
    
    num.nil? ? [] : num.sort
    
    (num || []).sort
    
    num.to_a.sort
    

    The latter two convert num to an empty array if num is nil, then sort the result. See NilClass.to_a.

提交回复
热议问题