返回空数组(Ruby) [英] Return empty array (Ruby)
问题描述
我正在尝试在 Ruby 中创建条件语句.如果我的各种数字数组为空或 nil,它应该返回一个空数组,否则它应该对数字进行排序.这是我目前所拥有的.
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. This is what I have so far.
num == nil || num.empty? ? return num : num.sort!
...其中 num 是我的数组.但是我收到以下错误:
...where num is my array. However I'm getting the following error:
syntax error, unexpected tIDENTIFIER, expecting ':'
如果 num 是数字数组或 nil,我会收到此错误.我不确定为什么这不起作用.有什么想法吗?
I get this error if num is an array of numbers or nil. I'm not sure why this isn't working. Any thoughts?
推荐答案
要修复您的代码,请将您拥有的内容更改为以下内容之一:
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
如果num
为nil
,后两者将num
转换为空数组,然后对结果进行排序.请参阅 NilClass.to_a.
The latter two convert num
to an empty array if num
is nil
, then sort the result. See NilClass.to_a.
这篇关于返回空数组(Ruby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!