Read also Yield.
Ruby block is "block" of code that can be passed around and invoke.
Ruby block has two styles: do...block
or { ... }
. Personally I use {}
for single line and do...block
for multiline.
You can use block_given?
to check if a block being passed in.
You can also implement the configuration of your library:
class Something
class Config
def initialize
@config = {}
end
def max_threads=(v)
@config[:max_threads] = v
end
def max_threads
@config[:max_threads]
end
end
def self.configure_client
yield Config.new
end
end
Something.configure_client do |config|
config.max_threads = 1
end
An example use of block to implement a Calculator
:
# Usage: 3*2-1
#
# Calculator.run do |calculator|
# calculator.add 3
# calculator.multiply 2
# calculator.substract 1
# end
# => 5
class Calculator
def self.run(init: 0)
yield Operations.new(init)
end
end
class Operations
def initialize(init = 0)
@init = init
end
def add(value)
self.init += value
end
def substract(value)
self.init -= value
end
def multiply(value)
self.init = init * value
end
def divide(value)
self.init = init / value.to_f
end
def clear
self.init = 0
end
private
attr_accessor :init
end