> books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]
> # To sort our books in ascending order, in-place
> books.sort! { |firstBook, secondBook| firstBook <=> secondBook }
> # Sort your books in descending order, in-place below
That will work - not sure if it will work for getting through the tutorial section… I think the answer they were looking for is to see you can reverse it like:
No. First, you misspelled “books”. Second, reverse! reverses in place, but you’re reversing the result of sort, not books – your code leaves books unchanged. This works:
def alphabetize (arr, rev=false)
if rev == true
puts arr.sort!.reverse!
else rev == false
puts arr.sort!
end
end
numbers = [4,7,1,3,4,9,6]
puts alphabetize(numbers)
It works, but still say…
“Oops, try again. It looks like your method doesn’t default to alphabetizing an array when it doesn’t receive a second parameter.”
------------------------------ Edit
i finally passed through the tutorial with this code
def alphabetize (arr, rev=false)
if rev == true
arr.sort!.reverse!
else rev == false
arr.sort! {|first, second| first <=> second}
end
end
numbers = [4,7,1,3,4,9,6]
puts alphabetize(numbers)
Can anyone explain me how below code going to sort the array in normal and reverse order…what does it compare…?
books.sort! { |firstBook, secondBook| firstBook <=> secondBook } # normal order
books.sort! { |firstBook, secondBook| secondBook<=>firstBook} # reverse order
Final code is this:
books = [“Charlie and the Chocolate Factory”, “War and Peace”, “Utopia”, “A Brief History of Time”, “A Wrinkle in Time”]
books.sort! { |firstBook, secondBook| firstBook <=> secondBook }
books.reverse! { |firstBook, secondBook| firstBook <=> secondBook }
The exercise is asking to use the example, if you do not want to use it, you can pass it using books.sort!.reverse!
If you want to follow the exercise use:
books.sort! { |firstBook, secondBook| secondBook <=> firstBook }
books = [“Charlie and the Chocolate Factory”, “War and Peace”, “Utopia”, “A Brief History of Time”, “A Wrinkle in Time”]
books.sort!
books.reverse!
puts books
Why do we have to put the { |firstBook, secondBook| firstBook <=> secondBook } part ?