如何定义一次代码块多次使用?

时间:2009-03-05 01:08:40

标签: ruby-on-rails ruby

通过代码块我的意思是:

def callBlock
  yield
  yield
end


callBlock { puts "In the block" } #this is the block

3 个答案:

答案 0 :(得分:6)

b = lambda { puts "this is the block" }
callBlock &b

b.call

带参数:

def call_block_name
    yield "Dave"
    yield "Mary"
    end

b = lambda { |s| puts "this is block #{s}" }
call_block_names &b

b.call("sam")

答案 1 :(得分:3)

使用Proc.new捕获一个块,例如

def callBlocks(*args, &block)
  args.each { |arg| arg.call }
  block.call if block_given?
end

my_proc1 = Proc.new { puts "proc1" }
my_proc2 = Proc.new { puts "proc2" }

callBlocks(my_proc1, my_proc1, my_proc2) {
  puts "block"
}

产生

proc1
proc1
proc2
block

想要一些论据吗?

def callBlocks(*args, &block)
  args.each { |arg| arg.call(1, 2, 3) }
  block.call(4, 5, 6) if block_given?
end

my_proc1 = Proc.new { |a, b, c| puts "proc1 with #{a}, #{b}, #{c}" }
my_proc2 = Proc.new { |a, *dummy| puts "proc2 only needs #{a}" }

callBlocks(my_proc1, my_proc1, my_proc2) { |*abc|
  puts "block with #{abc.join('/')}"
}

产生

proc1 with 1, 2, 3
proc1 with 1, 2, 3
proc2 only needs 1
block with 4/5/6

答案 2 :(得分:1)