4

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!

...where num is my array. However I'm getting the following error:

syntax error, unexpected tIDENTIFIER, expecting ':'

I get this error if num is an array of numbers or nil. I'm not sure why this isn't working. Any thoughts?

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

accepted because of that last code snippet. Well done good sir ;)
2

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

3 Comments

so is the return just assumed in Ruby?
Ruby always returns the value of the last executed statement. But if you want to return from somewhere else than the last statement, return comes in handy.
Or, just use if/then/else whose precedence is pretty much always what you would expect: if num == nil || num.empty? then return num else num.sort! end
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.