0

I have the following task description: Using an array, shopping_list, write the code to print the following words in sorted order: "potato", "cucumber", "banana", "persimmon".

Here is what I tried:

shopping_list = ["potato", "cucumber", "banana", "persimmon"]
shopping_list.sort
puts shopping_list

Why is this being marked incorrect?

1 Answer 1

2

You have to use shopping_list.sort!. Adding the exclamation at the end will save the existing array with those sorted values. When you print them again, it should be displayed sorted.

You can read more in the Ruby docs: https://ruby-doc.org/core-2.2.0/Array.html#method-i-sort-21.

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

4 Comments

The sort method returns a copy, which in the original code is thrown away. This might be confusing for people used to languages where it sorts in-place.
...but it's better to write puts shopping_list.sort (unless there is an explicit requirement to also modify shopping_list).
adding the exclamation at the end you're making it sound like ! is an operator.
This is a good suggestion for the OP's issue, but is does not answer the OP's question.

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.