-
-
Save ratbeard/154245 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# `irb` console session. | |
# Making a class, making it comparable, overriding its display formats, and using map! | |
# Make a class that mixins Comparable and defines <=> so it gets all <, ==, >, etc. | |
# Other methods like Array.sort will now work too | |
>> class Box | |
>> def <=>(other) | |
>> [source, color] <=> [other.source, other.color] | |
>> end | |
>> attr_accessor :color, :source | |
>> include Comparable | |
>> end | |
>> a, b = Box.new, Box.new | |
=> [#<Box:0x5627dc>, #<Box:0x5627c8>] | |
>> a.color = 'red'; a.source = 'MN' | |
=> "MN" | |
>> b.color = 'red'; b.source = 'MN' | |
=> "MN" | |
>> a == b | |
=> true | |
>> a.color = 'blue' | |
=> "blue" | |
>> a == b | |
=> false | |
# Make more boxes and sort dem! AZ (John McCain!) comes first | |
>> c, d = a.dup, a.dup | |
=> [#<Box:0x54b5dc @source="MN", @color="blue">, #<Box:0x54b5c8 @source="MN", @color="blue">] | |
>> c.source = 'AZ' | |
=> "AZ" | |
>> boxes = [a,b,c,d] | |
=> [#<Box:0x5627dc @source="MN", @color="blue">, #<Box:0x5627c8 @source="MN", @color="red">, #<Box:0x54b5dc @source="AZ", @color="blue">, #<Box:0x54b5c8 @source="MN", @color="blue">] | |
>> boxes.sort | |
=> [#<Box:0x54b5dc @source="AZ", @color="blue">, #<Box:0x5627dc @source="MN", @color="blue">, #<Box:0x54b5c8 @source="MN", @color="blue">, #<Box:0x5627c8 @source="MN", @color="red">] | |
# Now i re-open the Box class and override the inspect method to give a better output format while programming | |
>> class Box | |
>> def inspect | |
>> "<Box #{source} #{color}>" | |
>> end | |
>> end | |
=> nil | |
>> boxes.sort | |
=> [<Box AZ blue>, <Box MN blue>, <Box MN blue>, <Box MN red>] | |
# Make a better output format that might be displayed for an end user | |
>> class Box | |
>> def to_s | |
>> "#{color} Box from #{source}" | |
>> end | |
>> end | |
=> nil | |
>> puts boxes | |
blue Box from MN | |
blue Box from MN | |
blue Box from AZ | |
blue Box from MN | |
>> "I got a #{boxes.join ', '}" | |
=> "I got a blue Box from MN, blue Box from MN, blue Box from AZ, blue Box from MN" | |
# Call map to transform each element of boxes | |
# map! does the same and modifies the elements | |
>> boxes.map {|b| b.source } | |
=> ["MN", "MN", "AZ", "MN"] | |
>> boxes | |
=> [<Box MN blue>, <Box MN red>, <Box AZ blue>, <Box MN blue>] | |
>> boxes.map! {|b| b.source } | |
=> ["MN", "MN", "AZ", "MN"] | |
>> boxes | |
=> ["MN", "MN", "AZ", "MN"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment