In ruby, how do I write a "make" method in ruby?

I keep writing the same code in Ruby, which seems to benefit from the “do” code bits, but I'm not sure how to write this method.

I keep doing this code code that starts and ends with the same lines of code ...

x.increment!(:step_count) # same each time # ...then some different code each x.update_column(:step_description, "blerg message") # same each time 

I feel that it will benefit from doing something like this ...

 update_steps "blerg message" do # ...then some different code each end 

And then inside the "do" every time it executes the general code.

How can I make a method where I can use 'do'.

Thanks!

Edit: I consider it important not to close this because I did not know to look for "block" or "yield". People who may not know these conditions may end up looking for a “do.”

+6
source share
3 answers

Pass it a block as an argument

  def my_method(&block) do_something_the_same yield # calls whatever is inbetween "do" and "end" end 
+5
source

Creating methods that take a block is one of Ruby's most powerful features.

A common way to define such a method would be:

 def foo(*args, &block) # your code here yield # some more code end foo do # This code runs when yield is called end 

There are a few things you should know about this:

  • The &block not required. You can still use yield . But there are several reasons why you should add it to the method definition:

    • Indicates that your method accepts a block.
    • & basically converts the block to a proc object. This can be convenient, since you can pass it as a parameter to another method that takes a block. You just need to reapply & to make it block again.
    • Processing a proc object can be more powerful, as you can also set its binding.
  • You can pass yield arguments. The arguments you pass are local variables of the block. For example, in:

    [1,2,3] .each {| x | puts x}

    yield is called with one of the elements of the array at each iteration. The yield call with the argument is the same as block.call(a) , where a is the argument.

  • If your method encounters yield and there is no block, this will throw an exception. In some cases this may be correct. But if you want to have different behavior if no blocks are specified, can you use the block_given? method block_given? to check it out.

  • &block should be the last parameter in your method definition.
+5
source

Or you can also do this by calling block.call

 def update_steps(&block) block.call() end 
+1
source

All Articles