Alexandre
Alexandre

Reputation: 13318

Return the value from Ruby block

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

Answers (4)

tokland
tokland

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:

  • If you use 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.
  • It's not idiomatic to write method().
  • You need a default value to be used when no block is given (unless you fail before, of course).
  • You used different keys success and is_success, why?
  • You used :true and :false instead of real booleans, why?

Upvotes: 3

tokhi
tokhi

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

halfelf
halfelf

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

sawa
sawa

Reputation: 168249

Use call.

block.call

if block takes arguments, then give arguments:

block.call(whatever_arguments)

Upvotes: 2

Related Questions