Skip to content

Instantly share code, notes, and snippets.

Created July 24, 2009 14:00

Revisions

  1. @invalid-email-address Anonymous created this gist Jul 24, 2009.
    76 changes: 76 additions & 0 deletions snippet.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,76 @@
    # 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"]