块局部变量的语法 [英] Syntax for Block Local Variables

查看:57
本文介绍了块局部变量的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对定义块局部变量采用的好样式感到困惑.选择是:

I am confused about a good style to adopt to define block local variables. The choices are:

选择A:

method_that_calls_block { |v, w| puts v, w }

选择B:

method_that_calls_block { |v; w| puts v, w }

当我希望本地块具有默认值时,混乱就更加复杂了.我很困惑的选择是:

The confusion is compunded when I want the block local to have a default value. The choices I am confused about are:

选择C:

method_that_calls_block { |v, w = 1| puts v, w }

选择D:

method_that_calls_block { |v, w: 1| puts v, w }

是否有关于必须如何定义块局部变量的约定?

Is there a convention about how block local variables must be defined?

P.S.当我需要将默认值分配给块局部变量时,似乎; 语法也不起作用!奇怪的.

P.S. Also it seems the ; syntax does not work when I need to assign default value to a block local variable! Strange.

推荐答案

选择B无效.如@matt所示-这是有效的(尽管晦涩)语法(请参见此处:如何在Ruby中编写内联块以包含局部变量作用域?)

Choice B is not valid. As @matt indicated - it is a valid (though obscure) syntax (see here: How to write an inline block to contain local variable scope in Ruby?)

选择项C将默认值赋予 w ,这是常规值,而选择项D是默认值

Choice C gives a default value to w, which is a regular value, while Choice D is a syntax for default keyword argument.

这篇关于块局部变量的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆