开发者

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

users_allowed_to_be_viewed.map {|u|开发者_JAVA百科 "#{u.id},"}

but that gives 1,2,3,

What would be a short way to just get something like 1,2,3


an array?

from 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 is also aliased to Array#*, although that might make things a little obtuse:

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" 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜