yield
will imediately call the block passed to initalize. This means that @storeblock
will contain the result of calling yield
not the block itself. FYI, you are not putting @storedblock
into @@blockarray
If you want to store a block you can do something like this -
class BlockStore
def initialize
@blocks ||= []
end
def add_block(&block)
@blocks << block
end
def run_all_blocks
@blocks.each do |block|
block.call
end
end
end
block_store = BlockStore.new
block_store.add_block do
puts 'Hello!'
end
block_store.add_block do
puts 'World!'
end
puts 'About to run all blocks'
block_store.run_all_blocks
This gives you an output like the below. I've output 'About to run all blocks' before running the blocks to show that they are stored and then run later -
➜ ruby blocks.rb
About to run all blocks
Hello!
World!