Wednesday, December 30, 2009

Don't use return statement in call block

return statement in call block returns from surrounding method instead of returning from call block.

Following code snippet describes it with example.

def function1(&block)

callback_result = yield('value1', 'value2')

puts "call block returned: #{callback_result}"

end

def function2()

function1() do |param1, param2|
puts "block implementation of function2 with param1 => #{param1} & param2 => #{param2}"
return "#{param1} changed. #{param2} changed."
end

puts "next line after calling function1"

return "function2 returned"
end


def function3()

function1() do |param1, param2|
puts "block implementation of function3 with param1 => #{param1} & param2 => #{param2}"
"#{param1} changed. #{param2} changed."
end

puts "next line after calling function1"

return "function3 returned"
end

output of function2() is

block implementation of function2 with param1 => value1 & param2 => value2
"value1 changed. value2 changed."

Output of function3() is

block implementation of function3 with param1 => value1 & param2 => value2
call block returned: value1 changed. value2 changed.
next line after calling function1
"function3 returned"