I saw a line in a Rails app like this:
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.
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) }
.
So what's the Ruby grammar in this example?
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. 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] ]
.
You are correct that square brackets are not just used for arrays, you can also call 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.