Conditional Blocks in Ruby

Let's say I have a function with_foothat takes a block and wraps it around a piece of code, for example

with_foo do
  puts "hello!"
end

Now I would like to make a wrapping condition, for example

if do_with_foo?
  with_foo do
    puts "hello!"
  end
else
  puts "hello!" # without foo
end

Is there a way to write this shorter / more elegant, i.e. without repeating the code puts "hello!"?

+3
source share
5 answers

if you want to specify an argument with a block, this is possible.

above with foo, you can write a snippet like this:

whatever = proc {puts "hello"}
#build a proc object with a block
if do_with_foo?
  with_foo &whatever
#pass it to with_foo
else
  whatever.call
#normally call it
end
+6
source

Proof of concept using proxy template:

class BlockWrapper
  def initialize(obj, use_wrapper)
    @obj = obj
    @use_wrapper = use_wrapper
  end

  def method_missing(*args, &block)
    @use_wrapper ? @obj.send(*args, &block) : block.call
  end
end

module Kernel
  def wrap_if(use_wrapper)
    BlockWrapper.new(self, use_wrapper)        
  end
end

def with_foo
  puts "with_foo: start"
  yield
  puts "with_foo: end"
end

wrap_if(true).with_foo do 
  puts "hello!"
end

wrap_if(false).with_foo do 
  puts "hello, no with_foo here!"
end

Conclusion:

with_foo: start
hello!
with_foo: end
hello, no with_foo here!
+3
source

I think you can do this:

def without_foo &pr
  pr.call
end

send(do_with_foo?? "with_foo" : "without_foo") do
  puts "hello!"
end
+2
source

You can put the duplication code in the object Procand pass it to the method as a block, or call it directly.

hello = proc { puts 'hello' }

with_foo(&hello)
# OR
hello.call
+1
source
def simple_yielder
  yield
end
def maybe_with condition, with_method
  send( condition ? with_method : :simple_yielder ) { yield }
end

#...

maybe_with( do_with_foo?, :with_foo ) do
  puts "Hello?"
end
+1
source

All Articles