Return empty array (Ruby)

前端 未结 3 1073
天涯浪人
天涯浪人 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 08:53

    If you want to ensure that you work with an array, just call:

    Array(num).sort
    

    Because it works like this:

    Array(nil)    #=> []
    Array([])     #=> []
    Array([1, 2]) #=> [1, 2]
    
    0 讨论(0)
  • 2020-12-21 08:54

    It is because you put return num within a ternary operator construction. Precedence rule does not parse it as you wanted. Remove return, and it will not raise an error (although it will not work as you want to; nil will be returned when num is nil). Or, if you want to use return only when the condition is satisfied, then you should do (return num).

    But for your purpose, a better code is:

    num.to_a.sort
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题