12

I am calling the RestClient::Resource#get(additional_headers = {}, &block) method multiple times with the same block but on different Resources, I was wondering if there is a way to save the block into a variable, or to save it into a Proc convert it into a block each time.

Edit:

I did the following:

resource = RestClient::Resource.new('https://foo.com')
redirect  =  lambda do  |response, request, result, &block|
  if [301, 302, 307].include? response.code
     response.follow_redirection(request, result, &block)
   else
      response.return!(request, result, &block)
   end
end
@resp = resource.get (&redirect)

I get: Syntax error, unexpected tAMPER

4

1 回答 1

23
foo = lambda do |a,b,c|
   # your code here
end

bar.get(&foo)
jim.get(&foo)
jam.get(&foo)

在方法调用中的项目前面放置一个 & 符号,例如a.map!(&:to_i)调用该to_proc对象上的方法并将生成的 proc 作为块传递。定义可重用块的一些替代形式:

foo = Proc.new{ |a,b,c| ... }
foo = proc{ |a,b,c| ... }
foo = ->(a,b,c){ ... }

如果您正在使用块调用方法并且想要保存块以供以后重复使用,您可以通过在方法定义中使用&符号将块捕获为 proc 参数来实现:

class DoMany
  def initialize(*items,&block)
    @a = items
    @b = block # don't use an ampersand here
  end
  def do_first
    # Invoke the saved proc directly
    @b.call( @a.first )
  end
  def do_each
    # Pass the saved proc as a block
    @a.each(&@b)
  end
end

d = DoMany.new("Bob","Doug"){ |item| puts "Hello, #{item}!" }

d.do_first
#=> Hello, Bob!

d.do_each
#=> Hello, Bob!
#=> Hello, Doug!
于 2012-05-25T16:21:12.343 回答