Skip to content

Instantly share code, notes, and snippets.

@ilake
Created November 14, 2012 14:46
Show Gist options
  • Select an option

  • Save ilake/4072530 to your computer and use it in GitHub Desktop.

Select an option

Save ilake/4072530 to your computer and use it in GitHub Desktop.
LEVEL 6: BLOCKS
# YIELD - ARGUMENTS
def call_this_block
yield "tweet"
end
call_this_block { |myarg| puts myarg.upcase } # => TWEET
Timeline
def each
@user.friends.each do |friend|
friend.tweets.each { |tweet| yield tweet }
end
end
end
timeline = Timeline.new(user)
timeline.each { |tweet| puts tweet }
timeline.each { |tweet| tweet.cache }
class Timeline
def each
@user.friends.each do |friend|
friend.tweets.each { |tweet| yield tweet }
end
end
include Enumerable
end
timeline.sort_by { |tweet| tweet.created_at }
timeline.map { |tweet| tweet.status }
timeline.find_all { |tweet| tweet.status =~ /\@codeschool/ }
# Final Example
class Game
attr_accessor :name, :year, :system
attr_reader :created_at
def initialize(name, options={})
self.name = name
self.year = options[:year]
self.system = options[:system]
@created_at = Time.now
end
def play
emulate do |emulator|
emulator.play(self)
end
end
def screenshot
emulate do |emulator|
emulator.start(self)
emulator.screenshot
end
end
private
def emulate
begin
emulator = Emulator.new(system)
yield emulator
rescue Exception => e
puts "Emulator failed: #{e}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment