たとえば、繰り返されるタスクを処理するために、関数内に小さなラムダを作成することがよくあります (不自然な例):
def some_method(foo)
match = SOME_REGEX.match foo
has_component = lambda { |name|
match.names.include? name and not match[name].nil?
}
if has_component.call("street_name")
# ...
end
if has_component.call("house_number")
# ...
end
if has_component.call("entrance")
# ...
end
# ...
end
今、私はあなたのことを知りませんが、むしろ書きたいと思います:
if has_component "street_name"
# ...
end
if has_component "house_number"
# ...
end
if has_component "entrance"
# ...
end
私はRubyの内部動作に精通していませんが、ラムダ/プロシージャをdef
ined関数のように呼び出し可能にするためにできることはありますか?
クラス レベルでラムダ/プロシージャをメソッドとして定義したくない理由はいくつかあります。特に、呼び出し元のスコープにはアクセスできません。