Blocks and Sorting
Learn how to define your own methods, as well as how to use blocks to develop powerful sorting algorithms.
StartKey Concepts
Review core concepts you need to learn to master this subject
Ruby Combined Comparison Operator
Ruby Method Splat
Ruby Block Parameter
Ruby Return
Ruby Sort Method
Ruby Method Parameters & Arguments
Ruby method
Ruby Block
Ruby Combined Comparison Operator
Ruby Combined Comparison Operator
puts "Keanu" <=> "Adrianna" # The first letters of each word are compared in ASCII order and since "K" comes after "A", 1 is printed.
puts 1 <=> 2 # -1
puts 3 <=> 3 # 0
#<=> can also be used inside of a block and to sort values in descending order:
my_array = [3, 0, 8, 7, 1, 6, 5, 9, 4]
my_array.sort! { |first_num, second_num| second_num <=> first_num }
print my_array
#Output => [9, 8, 7, 6, 5, 4, 3, 1, 0]
In Ruby, the combined comparison operator, <=>
, also known as the spaceship operator is used to compare two objects. It returns 0
if the first operand equals the second, 1
if the first operand is greater than the second, and -1
if the first operand is less than the second.
Methods, Blocks, & Sorting
Lesson 1 of 2