简体   繁体   中英

How to sort this array in ruby?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM