Save and reuse block for method calls

I call the RestClient :: Resource # get (extra_headers = {}, & block) method several times with the same block, but with different resources, I was wondering if there is a way to save the block in a variable or save it in Proc to convert it into the block every time.

Edit:

I have done 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

+8
ruby
source share
1 answer
 foo = lambda do |a,b,c| # your code here end bar.get(&foo) jim.get(&foo) jam.get(&foo) 

Placing an ampersand in front of an element in a method call, for example. a.map!(&:to_i) calls the to_proc method on this object and passes the resulting proc as a block. Some alternative forms of defining your reusable block:

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

If you call a method with a block, and you want to save this block for reuse later, you can do this by using the ampersand in the method definition to capture the block as the proc parameter:

 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! 
+16
source share

All Articles