简体   繁体   English

Ruby on Rails:在数组中的元素之间插入逗号的简短手段?

[英]Ruby on Rails: short hand to put commas in between elements in an array?

users_allowed_to_be_viewed.map {|u| "#{u.id},"}

but that gives 1,2,3, 但这给了1,2,3,

What would be a short way to just get something like 1,2,3 什么是一个简短的方法来获得像1,2,3这样的东西

an array? 数组?

from http://ruby-doc.org/core/classes/Array.html 来自http://ruby-doc.org/core/classes/Array.html

 array.join(sep=$,) → str

Returns a string created by converting each element of the array to a string, separated by sep.

       [ "a", "b", "c" ].join        #=> "abc"
       [ "a", "b", "c" ].join("-")   #=> "a-b-c"
users_allowed_to_be_viewed.map{|u| u.id}.join(",")
users_allowed_to_be_viewed.map(&:id).join(',')

Array#join也是Array#*别名,虽然这可能会让事情变得有点迟钝:

users_allowed_to_be_viewed.map(&:id) * ','
users_allowed_to_be_viewed.join ',' 

ruby-1.8.7-p299 > users_allowed_to_be_viewed = [1,2,3]
   => [1, 2, 3] 
ruby-1.8.7-p299 > users_allowed_to_be_viewed.join ',' 
    => "1,2,3" 

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

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