Last active
December 7, 2015 00:29
-
-
Save franzejr/ae0b4e4f1d5a889632ae to your computer and use it in GitHub Desktop.
Ruby Blocks examples
This file contains 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
## Execute Around | |
def time_it(label) | |
start_time = Time.now | |
yield | |
elapsed_time = Time.now - start_time | |
puts "#{label} took #{elapsed_time} seconds" | |
end | |
time_it("Sleepy code") do | |
#run some code | |
sleep(0.5) | |
end | |
# Checking something and using yield | |
def with_checking(description) | |
puts "Checking #{description}" | |
result = yield | |
result ? "Ok" : "Failed" | |
end | |
with_checking("temperature") { 3 < 5 } | |
with_checking("another_example") { 3 < 5 } | |
# Block initializer | |
module Jem | |
class Specification | |
attr_accessor :name, :description, :version | |
def initialize | |
@version = '1.0.0' | |
yield(self) if block_given? | |
end | |
end | |
end | |
spec = Jem::Specification.new do |s| | |
s.description = "Description" | |
s.version = "2.0.0" | |
s.name = "My Jem" | |
end | |
## Manage Resources | |
class File | |
def self.my_open(filename, mode) | |
file = self.new(filename, mode) | |
return file unless block_given? | |
begin | |
yield(file) | |
ensure | |
file.close | |
end | |
end | |
end | |
File.my_open("letter.txt", "w") do |f| | |
f.puts "Hello" | |
f.puts "Goodbye" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment