简体   繁体   English

方括号在这里意味着什么?

[英]What do the square brackets mean here?

I saw a line in a Rails app like this: 我在Rails应用程序中看到了这样一行:

Order::PAYMENT_TYPES.map {|p| [t('.payment_type.'+p), p]}

PAYMENT_TYPE is a string array, and the letter t is used for i18n in Rails. PAYMENT_TYPE是一个字符串数组,字母t用于Rails中的i18n。

I'm not sure how the square brackets are used here. 我不确定方括号在这里是如何使用的。 Apparently they are not for arrays or methods. 显然它们不适用于数组或方法。 And I will rewrite this to just {|p| t('.payment_type.'+p) } 我会将其重写为{|p| t('.payment_type.'+p) } {|p| t('.payment_type.'+p) } . {|p| t('.payment_type.'+p) }

So what's the Ruby grammar in this example? 那么这个例子中的Ruby语法是什么?

Apparently they are not for arrays or methods 显然它们不适用于数组或方法

Well, it is an array literal 嗯,这一个数组文字

[t('.payment_type.'+p), p]
# ^ first element       ^ second

I will rewrite this to just ... 我会把它改写成......

If this will work for you, go ahead. 如果这对您有用,请继续。 We don't know your app's specifics. 我们不知道您应用的具体细节。

Ruby returns the last statement from a method or a block. Ruby从方法或块返回最后一个语句。 In this case, with the brackets, the block returns an array of two items, so calling that block in map , if PAYMENT_TYPES had three items, would result in something like [ [a1, b1], [a2, b2], [a3, b3] ] . 在这种情况下,使用括号,块返回一个包含两个项的数组,因此如果PAYMENT_TYPES有三个项,则在map调用该块将导致类似[ [a1, b1], [a2, b2], [a3, b3] ]

You are correct that square brackets are not just used for arrays, you can also call Procs. 你是正确的,方括号不仅用于数组,你也可以调用Procs。

proc = lambda { |name| "Hello, #{name}" }
proc.call('Bob')
=> "Hello, Bob"

proc = lambda { |name| "Hello, #{name}" }
proc['Bob']
=> "Hello, Bob"

But in this case, as others have indicated, a new array is being returned resulting in a nested array of arrays. 但在这种情况下,正如其他人所指出的那样,正在返回一个新数组,从而产生一个嵌套的数组数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM