2015-04-05 165 views
0

不叫我尝试这种代码:区块红宝石

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

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

输出怎么会是“不堵”? 我对m构造块的方式有什么问题? {“testing”}会起作用。

+0

这已在[Ruby Block Syntax Error](http://StackOverflow.Com/q/6854283/)中得到解答,[传递给'each'的代码块与括号一起使用,但不与'do'-'end '(ruby)](http://StackOverflow.Com/q/6718340/),[块定义 - 大括号和'''''''end'之间的区别?](http://StackOverflow.Com/q/6179442/ ),[没有'do''end的Ruby多行块]](http://StackOverflow.Com/q/3680097/),[使用'do'块vs括号'{}'](http://StackOverflow.Com/q/2122380 /),[这些块的编码风格在Ruby中的区别或价值是什么?](http://StackOverflow.Com/q/533008/),... – 2015-04-05 12:26:42

+0

... [Ruby块和unparenthesized参数](http ://StackOverflow.Com/q/420147/),[为什么'do' /'end'和'{}'总是等价的?](http://StackOverflow.Com/q/7487664/),[ Ruby块中的奇怪缺陷](http://StackOverflow.Com/q/7620804/),[将块传递给方法 - Ruby](http:/ /StackOverflow.Com/q/10909496/),['instance_eval' block not supplied?](http://StackOverflow.Com/q/12175788/),[block syntax differences cause“LocalJumpError:no block given(yield) '']](http://StackOverflow.Com/q/18623447/),... – 2015-04-05 12:27:43

+0

... ['instance_eval'不能与'do' /'end'块一起使用,只能使用'{}'-blocks](http: //StackOverflow.Com/q/21042867/),[''proc'在与'do'' end'一起使用时抛出错误](http://StackOverflow.Com/q/25217274/)。 – 2015-04-05 12:28:06

回答

1

添加括号puts

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

输出为6

您的代码就相当于

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

谢谢。但是如何使m {“testing”}起作用? – meizin 2015-04-05 04:40:19

+0

我现在知道了。谢谢:) – meizin 2015-04-05 04:53:18

1

删除puts

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

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

它将始终返回m块中的最后一条语句。