7

with_fooブロックを受け取り、それをコードの一部にラップする関数があるとします。

with_foo do
  puts "hello!"
end

今、次のようにラッピングを条件付きにしたいと思います

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

コードを繰り返さなくても、これをより短く/よりエレガントに書く方法はありますputs "hello!"か?

4

5 に答える 5

7

ブロックで引数を指定したい場合は可能です。

上記with fooのように、そのようなスニペットを書くことができます:

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
于 2012-05-24T12:03:31.287 に答える
3

プロキシパターンを使用した概念実証:

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

出力:

with_foo: start
hello!
with_foo: end
hello, no with_foo here!
于 2012-05-24T12:50:30.087 に答える
2

私はあなたがこれを行うことができると思います:

def without_foo &pr
  pr.call
end

send(do_with_foo?? "with_foo" : "without_foo") do
  puts "hello!"
end
于 2012-05-24T14:48:26.180 に答える
1

複製コードをオブジェクトに入れて、Procブロックとしてメソッドに渡すか、直接呼び出すことができます。

hello = proc { puts 'hello' }

with_foo(&hello)
# OR
hello.call
于 2012-05-24T12:03:09.253 に答える
1
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
于 2012-05-24T22:20:04.137 に答える