开发者

Passing multiple code blocks as arguments in Ruby

开发者 https://www.devze.com 2022-12-23 19:17 出处:网络
I have a method which takes a code block. def opportunity @opportunities += 1 if yield @performances +=1 end

I have a method which takes a code block.

def opportunity
  @opportunities += 1
  if yield
    @performances +=1
  end
end

and I call it like this:

opportunity { @some_array.empty? }

But how do I pass it more than one code block so that I could use yield twice, something like this:

def opportunity
  if yield_1
    @opportunities += 1
  end
  if yield_2
    @performances +=1
  end
end

and:

开发者_开发技巧
opportunity {@some_other_array.empty?} { @some_array.empty? }

I am aware that this example could be done without yield, but it's just to illustrate.


You can't pass multiple blocks, per se, but you can pass multiple procs or lambdas:

Using 1.9 syntax:

opportunity ->{ @some_array.empty? }, ->{ @some_other_array.empty? }

and in the method itself:

def opportunity(lambda1, lambda2)
  if lambda1.()
    @opportunities += 1
  end
  if lambda2.()
    @performances += 1
  end
end


I'm really late to the Ruby party - just learning it now. And this is an old post, but I just had this question myself so appreciate it being here. I came up with a higher order function possibility, but I couldn't get rid of the dummy variable. So I lived with it.

@opportunities = 0
@performances = 0

  def opportunity &b1
    method(
        def helper b1, dummy, &b2
            if b1.call 
                @opportunities += 1
            end
            if b2.call 
                @performances += 1
            end
        end).curry[b1]
  end

  opportunity {true}[nil]{true} 
  p [@opportunities, @performances]     #[1, 1]
  opportunity {false}[nil]{true}
  p [@opportunities, @performances]     #[1, 2]
  opportunity {false}[nil]{true}
  p [@opportunities, @performances]     #[1, 3]
  opportunity {false}[nil]{false}
  p [@opportunities, @performances]     #[1, 3]
  opportunity {true}[nil]{false}
  p [@opportunities, @performances]     #[2, 3]
  opportunity {true}[nil]{true}
  p [@opportunities, @performances]     #[3, 4]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号