如何运行存储块?

时间:2015-08-31 21:25:41

标签: ruby

我有一个存储块的类,我想稍后运行一个块。我该怎么办呢?

class StoreBlocks
  @@blockarray = []
  def initialize
    @storedblock = yield
    @@blockarray << self
  end
  attr_reader :storedblock
  def self.getblock
    @@blockarray
  end
end

StoreBlocks.new do
  # cool codey stuff
end

# do other things

我如何运行StoreBlocks.getblock[0].storedblock

2 个答案:

答案 0 :(得分:1)

= yield将分配传递块的返回值,而不是块本身。您需要将您的课程改为:

class StoreBlocks
  attr_accessor :storedblock
  @@blockarray
  def initialize &block
    @storedblock = block
    @@blockarray << self
  end
  def self.getblock
    @@blockarray
  end
end

&表示传递给initialize的块将转换为Proc并分配给名为block的参数,而不是将其存储在实例变量中。你可以称之为:

StoreBlocks.getblock[0].storedblock.call()

答案 1 :(得分:1)

yield将立即调用传递给initalize的块。这意味着@storeblock将包含调用yield而不是块本身的结果。仅供参考,您没有将@storedblock放入@@blockarray

如果你想存储一个块你可以做这样的事情 -

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

这将为您提供如下输出。我已输出&#39;关于运行所有块&#39;在运行块之前显示它们已存储然后再运行 -

➜  ruby blocks.rb 
About to run all blocks
Hello!
World!