All posts

How to add a guard to a block in Ruby

 ruby

“I don’t want specific items in this array to be processed by this ruby block” is another scenario often faced when programming in Ruby. Like the post on extiting from a block, I think a lot of people try to return from the block as a first attempt, but that doesn’t return from the block, it returns from the entire method, which in this case isn’t the desired behavior. So when you need to exit the current iteration of a block you can use the next keyword.

[1,2,3,4].each{|int| next if int == 3}

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).