0

I tried this code:

def m
  return yield if block_given?
  "no block"
end

puts m do
  x = 2
  y = 3
  x*y
end

How come the output is "no block"? What's wrong with my way of constructing the block to m? {"testing"} will work.

meizin
  • 221
  • 2
  • 8
  • This has already been answered in [Ruby Block Syntax Error](http://StackOverflow.Com/q/6854283/), [Code block passed to `each` works with brackets but not with `do`-`end` (ruby)](http://StackOverflow.Com/q/6718340/), [Block definition - difference between braces and `do`-`end` ?](http://StackOverflow.Com/q/6179442/), [Ruby multiline block without `do` `end`](http://StackOverflow.Com/q/3680097/), [Using `do` block vs brackets `{}`](http://StackOverflow.Com/q/2122380/), [What is the difference or value of these block coding styles in Ruby?](http://StackOverflow.Com/q/533008/), … – Jörg W Mittag Apr 05 '15 at 12:26
  • … [Ruby block and unparenthesized arguments](http://StackOverflow.Com/q/420147/), [Why aren't `do`/`end` and `{}` always equivalent?](http://StackOverflow.Com/q/7487664/), [Wierd imperfection in Ruby blocks](http://StackOverflow.Com/q/7620804/), [Passing block into a method - Ruby](http://StackOverflow.Com/q/10909496/), [`instance_eval` block not supplied?](http://StackOverflow.Com/q/12175788/), [block syntax difference causes “`LocalJumpError: no block given (yield)`”](http://StackOverflow.Com/q/18623447/), … – Jörg W Mittag Apr 05 '15 at 12:27
  • … [`instance_eval` does not work with `do`/`end` block, only with `{}`-blocks](http://StackOverflow.Com/q/21042867/), and [`Proc` throws error when used with `do` `end`](http://StackOverflow.Com/q/25217274/). – Jörg W Mittag Apr 05 '15 at 12:28

2 Answers2

1

Add parentheses to puts

puts(m do
  x = 2
  y = 3
  x * y
end)

The output is 6.

Your code is equivalent to

puts(m) do 
  x = 2
  y = 3
  x * y
end
mrahmiao
  • 1,291
  • 1
  • 10
  • 22
1

Remove the puts:

def m
  return yield if block_given?
  "no block"
end

m do
  x = 2
  y = 3
  x*y
end

It will always return the last statement in the m block.

Victor
  • 13,010
  • 18
  • 83
  • 146