Mix-in Example

Just trying to create an example for the mix-in use.

class Days
  include Enumerable

  def initialize(days = [])
    @days = days.map {|x| Day.new(x) }
  end

  def << (day)
    @days << Day.new(day)
  end

  def each
    @days.each do |day|
      yield day
    end
  end

  def to_s
    @days.join(", ")
  end
end

class Day
  include Comparable

  def initialize(day)
    @day = day
  end

  def <=> (other)
    get_index(@day) <=> get_index(other.to_s)
  end

  def +(x)
    index = (get_index(@day) + x) % DAYS.length
    DAYS[index]
  end

  def to_s
    @day
  end

private
  DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

  def get_index(str)
    DAYS.index(str.capitalize)
  end
end

puts "[Compare]"
puts Day.new("Sat") < Day.new("Mon")
# => false
puts Day.new("Wed") > Day.new("Tue")
# => true

days = Days.new(["Wed", "Mon", "Tue", "Sun"])
days << "Sat"

puts "[List]"
puts days
# => Wed, Mon, Tue, Sun, Sat

puts "[Sort]"
puts days.sort.join(", ")
# => Sun, Mon, Tue, Wed, Sat

puts "[Select]"
puts days.select { |x| x >= "Tue" }.join(", ")
# => Wed, Tue, Sat

puts "[Map]"
puts days.map {|x| x + 1 }.join(", ")
# => Thu, Tue, Wed, Mon, Sun

puts "[Max]"
puts days.max
# => Sat
Advertisements

Posted on February 10, 2013, in Ruby. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: