Skip to content

Instantly share code, notes, and snippets.

@dscataglini
Created November 19, 2010 22:04
Show Gist options
  • Save dscataglini/707277 to your computer and use it in GitHub Desktop.
Save dscataglini/707277 to your computer and use it in GitHub Desktop.
It should execute the block only if the passed in value is true, and return the conditional. Caller can optionally pass a value to be yield
def yield_if?(bool = false, value = nil)
yield(value) if bool && block_given?
bool
end
@dscataglini
Copy link
Author

Too many times I end up writing code that looks like this

def foo
  ret = some_expensive_call
  do_something if ret
  ret
end

or
def foo
if ret = some_expensive_call
do_something
end
ret
end

What I want is:

def foo
  yield_if?(some_expensive_call) do
    do_something
  end
end

I could do this:

def foo
  returning( some_expensive_call, &lambda{ |boolean| do_something if boolean } )
end

Although I am not sure about the name for it. I also wonder if it already exists.
It calls the block only if the conditional is true, but I want the result of the conditional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment