Skip to content

Instantly share code, notes, and snippets.

@tnoworyta
Created July 17, 2016 14:51
Show Gist options
  • Save tnoworyta/f5d9c2df98aebc81737c240570c4bf2c to your computer and use it in GitHub Desktop.
Save tnoworyta/f5d9c2df98aebc81737c240570c4bf2c to your computer and use it in GitHub Desktop.
puts "block - yield ========================================================="
class FtpManager
def upload_file(file_path='file1')
open_connection do |connection|
puts "do something with #{connection}"
end
end
def remove_file(file_path='file')
open_connection do |connection|
puts "do something with #{connection}"
end
end
private
def open_connection
puts "open connection"
yield('<connection_object>')
puts "close connection / handle errors if raised"
end
end
puts ":: call remove_file"
FtpManager.new.remove_file
puts "block - yield - optional =============================================="
class FtpManager2
def upload_file(file_path='file1')
open_connection do |connection|
puts "do something with #{connection}"
end
end
def remove_file(file_path='file')
open_connection do |connection|
puts "do something with #{connection}"
end
end
def open_connection
puts "open connection"
if block_given?
yield('<connection_object>')
puts "close connection / handle errors if raised"
else
'<connection_object>'
end
end
end
puts ":: call remove_file"
FtpManager2.new.remove_file
puts ":: call open_connection"
puts FtpManager2.new.open_connection
puts "block - call =========================================================="
class FtpManager3
def upload_file(file_path='file1')
open_connection do |connection|
puts "do something with #{connection}"
end
end
def remove_file(file_path='file')
open_connection do |connection|
puts "do something with #{connection}"
end
end
private
def open_connection(&block)
puts "open connection"
block.call('<connection_object>')
puts "close connection / handle errors if raised"
end
end
puts ":: call remove_file"
FtpManager3.new.remove_file
@tnoworyta
Copy link
Author

tnoworyta commented Jul 17, 2016

Other example:

def wrap_in_h1
  "<h1>#{yield}</h1>"
end

wrap_in_h1 { "Here's my heading" }

# => "<h1>Here's my heading</h1>"

@tnoworyta
Copy link
Author

There is no functional difference between yield and block.call. Some developers prefer the more explicit style with block.call.

@tnoworyta
Copy link
Author

We can pass block of code to any method but it will be executed only if it calls yield or block.call
When we pass something other that block of code, it will try to execute on it method to_proc.

That's why this shortcut works:

puts ['ala', 'ma', 'kota'].map { |word| word.capitalize }.join(" ")
puts ['ala', 'ma', 'kota'].map(&:capitalize).join(" ")

It works because Symbol implements #to_proc method which returns block to #map that can be executed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment