官术网_书友最值得收藏!

Return behavior

Secondly, lambdas and procs have different behaviors when it comes to returning values from methods. To see this, I'm going to create a method called my_method:

def my_method 
x = lambda {return}
x.call
p "Text within the method"
end

my_method

If I run this method, it prints out "Text within the method":

Now, let's try exactly the same implementation with a proc:

def my_method 
x = Proc.new {return}
x.call
p "Text within the method"
end

my_method

When you run it this time, it returns a value of nil.

What happened is that when the proc saw the return word, it exited out of the entire method and returned a nil value. However, in the case of the lambda, it processed the remaining part of the method.

So, these are the subtle and yet important differences between lambdas and procs.

主站蜘蛛池模板: 衡阳市| 陵川县| 龙里县| 黑山县| 云林县| 桐乡市| 瑞昌市| 苍南县| 宜州市| 武穴市| 许昌市| 金溪县| 甘南县| 常熟市| 柳林县| 吉木乃县| 长乐市| 徐州市| 汉沽区| 东丰县| 蓝田县| 长葛市| 宁南县| 九江县| 开江县| 南通市| 大悟县| 高平市| 湖南省| 县级市| 神池县| 嘉善县| 含山县| 马关县| 安乡县| 台湾省| 军事| 肇州县| 赣州市| 毕节市| 梁山县|