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

时间:2010-08-06 13:15:57

标签: ruby-on-rails ruby

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

但是这会给1,2,3,

获得1,2,3

之类的简短方法

4 个答案:

答案 0 :(得分:5)

一个数组?

来自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"

答案 1 :(得分:4)

users_allowed_to_be_viewed.map{|u| u.id}.join(",")

答案 2 :(得分:3)

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

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

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

答案 3 :(得分:2)

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"