Reputation: 13318
I have a method
def method1(&block)
#.............
if condition == "yes"
yield if block_given?
{success: :true, value: **value returned from the block**}
else
{is_success: :false, value: get_errors_array() }
end
end
How do retrieve the value from &block
? Should the &block
use return
keyword for that?
Upvotes: 1
Views: 2377
Reputation: 67900
def method1
fail("Needs block") unless block_given?
if condition
{success: true, value: yield}
else
{success: false, value: get_errors_array}
end
end
Notes and questions:
yield
is not idiomatic to put &block
in the method arguments. If you want to require the block write fail("Need blocks") unless block_given?
. You can leave it out and then you'll get a "LocalJumpError: no block given", which is also ok.yield
is an expression, not an statement.method()
.success
and is_success
, why?:true
and :false
instead of real booleans, why?Upvotes: 3
Reputation: 21616
The & prefix operator will allow a method to capture a passed block as a named parameter.
def wrap &b
print "dog barks: "
3.times(&b)
print "\t"
end
wrap { print "Wow! " } # Wow! Wow! wow!
Upvotes: -1
Reputation: 10107
Nope, there shouldn't be a return
in a block here. The "return" value of block is the value of last expression in it.
value_returned = yield if block_given?
Upvotes: 6
Reputation: 168249
Use call
.
block.call
if block
takes arguments, then give arguments:
block.call(whatever_arguments)
Upvotes: 2