Question

I'd expect this code:

def print_call_and_return(string, &block)
  puts string
  block.call unless !block
  "return"
end

puts print_call_and_return("parameter") do
  puts "block"
end

to print:

parameter
block
return

however it actually prints the following:

irb(main):011:0> puts print_call_and_return("parameter") do
irb(main):012:1* puts "block"
irb(main):013:1> end
parameter
return
=> nil

could someone explain this?

Was it helpful?

Solution

This does work:

puts print_call_and_return("parameter") { puts "block" }

I think the reason has to do with operator precedence. do/end has higher precedence than {} blocks.

puts print_call_and_return("parameter") do
  puts "block"
end

is the same as

puts(print_call_and_return("parameter")){ puts "block" }

OTHER TIPS

print_call_and_return("parameter") prints "parameter" and returns "return"

so the output so far is "parameter"

puts print_call_and_return("parameter") does a puts on the return value, which is "return"

so the output so far is "parameter", then "return"

puts answers nil, and puts do #anything does nothing. do is weaker than any expression, so the block applies to (puts function) do, not puts (function do).

output is as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top