1

I have some code that needs to be called directly or passed to another method that must take a block. Pseudocode:

class Foo
  def bar
    if condition
      return method_that_needs_a_block!('string', named1:, named2:) do
        shared_method('a', 'b')
      end
    end

    shared_method('a', 'b')
  end

  def shared_method(arg1, arg2)
    puts arg1
    puts arg2
  end

end

You can see the method that must take a block method_that_needs_a_block has a string for the first parameter and the rest are named parameters. How can shared_method be used as either a method or a block and still be able to pass the arguments to it? I've attempted making the method a lambda but I'm still unsure how to use it within the block context.

ryanpback
  • 275
  • 4
  • 17
  • Your question is a bit unclear but maybe you are looking for [`block_given?`](https://ruby-doc.org/core-3.0.2/Kernel.html#method-i-block_given-3F) – engineersmnky Feb 09 '23 at 14:13
  • @engineersmnky I wasn't sure if the naming would all make sense. I was trying to give the most detail without worrying about naming. The method that accepts a block is from a gem, I don't have access to it other than to call it. I have a method that I need to call either directly or pass as a block to the gem's method. Let me know if you have other questions. Trying to fit this all into my allotted characters. – ryanpback Feb 09 '23 at 17:04

1 Answers1

0

I'm not sure I 100% understand the question but if you want to pass a method as a block use &method(:method_name).

class Foo
  def bar(a, b, &block)
    if block_given?
      TheGemToEndAllGems.frobnobize(a, b, &block)
    else
      TheGemToEndAllGems.frobnobize(a, b, &method(:default_method))
    end
  end

  def default_method(a, b)
    puts "default method says: #{a} #{b}"
  end
end
module TheGemToEndAllGems
  def self.frobnobize(a, b)
    yield a, b if block_given?
  end
end 
irb(main):090:0> Foo.new.bar('Hello', 'World')
default method says: Hello World

Since parens are optional in Ruby there is a special method method which is used to get refences to methods - it returns a Method object. This is somewhat like a function reference in other languages.

Since blocks in Ruby are not actually objects and passed differently the & operator is used to turn the method object into a Proc.

max
  • 96,212
  • 14
  • 104
  • 165
  • I probably could have done a better job explaining, but I'll try to go off your example. In the case of `frobonize`, the method from the gem I'm using, it takes its own set of arguments unrelated to the arguments that `default_method` needs. So I believe I'm unable to pass additional args to an already-defined parameter list. I really just need to be able to pass `default_method` with its args to be called by `frobonize`. – ryanpback Feb 13 '23 at 17:45