Ordering with Comparable
Lesson 37 of 48 in Coddy's Ruby for C# Developers course.
C# sorting can use IComparable or an IComparer with negative, zero and positive comparison results. Ruby Comparable derives relational helpers from <=>, while sort_by computes keys. A zero ordering comparison does not establish object identity. Distinguish mutating collection sorting from methods that return a new ordered result.
C#: complete program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
var values=new List<int>{3,1,2}; values.Sort((a,b)=>a.CompareTo(b)); Console.WriteLine(values[0]);
Ruby: complete program
words = ["pear", "a", "fig"]
puts words.sort_by { |word| word.length }.join(",")Challenge
EasyDefine Priority(rank,label), read-only rank and label, include Comparable, and implement <=> ordered by rank then label. solve reads rank:label tokens, sorts Priority objects and returns labels comma-separated, or none.
Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.
Your code goes in exercise.rb, priority.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'priority'
def check(value)
raise 'Public API check failed' unless value
end
a = Priority.new(2, "a"); b = Priority.new(2, "b")
check(a.rank == 2 && a.label == "a" && a < b && a == Priority.new(2, "a"))
check(Priority.ancestors.include?(Comparable))
puts solve(STDIN.read)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for C# Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip4Mutation and Errors
Mutation and AliasesNil and Optional ValuesExceptions and ValidationEnsure and CleanupRecap: Safe Ratio7Objects in Practice
Ordering with ComparableCopies and Frozen ValuesLambdas and Captured StateCustom EnumerableRecap: Callable FilterRecap: Limited Store2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler