How to make a method accept a do block

Hey I was working on adding some tests to my projects and would really like to be able to utilize the do block! How do I set up a method to accept the do block?

The following code has the exact same behaviour in Imba 1.5.2 and Imba v2 on scrimba:

class Dog
	def bark

let dog = 

let result1 = dog.bark do console.log("doesn't print")

let result = [1,2,3].map do console.log("prints")  <-- I want to make my method work like tihs

Console output:


The fact that .map do works suggests that this should be possible, I just am having trouble guessing the correct syntax! In ruby I would add yield in the methods block and once the yield was reached it would execute the passed do block.

Thanks in advance for the help!

1 Like

So in your example the bark method needs to take an argument so that’s why it’s not working. In other words you are never calling the method, you could do

	def bark m

That would run your part and print doesn't print.

Below is another example, note that the last one with ampersand is normally used when the block is not passed in as the last argument. In the example below there is only one argument to the method performWork so it does not really matter but wanted to highlight that. Does it make sense?

class WorkerQueue
	def performWork callback
		console.log('# doing some work...')	

let w = 

let someWork = w.performWork do

w.performWork(&) do console.log('oneliner')

Thanks, That was very clear and unblocked me. For anyone else reading this coming from a ruby background, there is no yield keyword equivalent, because the block of code passed to a method is passed as an argument, you can still execute it arbitrarily within your block of code though by simply calling that argument.

This does seem have the unfortunate result that there are not methods that optionally accept a block, either a method always expects a block to be passed to it or it never does, but for the most part consistency never hurt anyone