我有一个数组:
array = ["10", "20", "50", "99"]
我想将它转换为一个简单的逗号分隔字符串列表,如下所示:
"10", "20", "50", "99"
我有一个数组:
array = ["10", "20", "50", "99"]
我想将它转换为一个简单的逗号分隔字符串列表,如下所示:
"10", "20", "50", "99"
array.join(',')
几乎可以实现你想要的功能;它不会保留值周围的引号或后面的空格。
如果要保留引号和空格:array.map{|item| %Q{"#{item}"}}.join(', ')
这将打印"\"10\", \"20\", \"50\", \"99\""
。 假设问题确实要求单个字符串,则转义引号是必需的。
关于%Q
的文档:字符串文字。
你可以像另一个答案中建议的那样使用inspect
,我认为这是个人喜好。 对于自己选择,请查看inspect
的源代码。
有用的提示:array.to_sentence
将给您提供“1、2、3和4”样式的输出,这可能很好!
["10", "20", "50","99"].map(&:inspect).join(', ') # => '"10", "20", "50", "99"'
map{|v| v.to_s.inspect}
可以处理整数和字符串类型的值。 - tadman"
时会发生什么? - dbenhur["10", ''].map(&:inspect).join(', ') # => '"10", ""'
- sczizzoinspect
不应该以这种方式使用。 - Mark Thomas这里:
array.map {|str| "\"#{str}\""}.join(',')
\
是转义字符,所以 \"
代表字符 "
,而开头和结尾的简单 "
是字符串定界符。您可能正在使用 p x
打印结果,它等同于 puts x.inspect
,请尝试改为使用 puts x
。 - Patrick Oscity"""
。 - Linuxios"""
时,你会得到什么?我猜不会有太多东西。 - tadman几个答案都提供了使用 #map
、#inspect
、#join
的解决方案。但是,所有这些方案都无法正确处理包含嵌入逗号和/或字符串定界符元素的边缘情况的 CSV 编码细节。
使用标准库类CSV可能是一个更好的主意,而不是自己编写代码。
irb> require 'csv'
=> true
irb> a = [10,'1,234','J.R. "Bob" Dobbs',3.14159]
=> [10, "1,234", "J.R. \"Bob\" Dobbs", 3.14159]
irb> puts a.to_csv
10,"1,234","J.R. ""Bob"" Dobbs",3.14159
如果这种编码不需要考虑嵌入分隔符,或者只是为某个内部表示而设计,那么map.join解决方案已经足够了,但是如果要生成数据以便与其他程序交换,这些程序期望逗号分隔值(CSV)作为一种通用的表示形式,则它们将失败。
"'#{["John Oliver", "Sam Tom"].join("','")}'"
to
'John Oliver', 'Sam Tom'
来源: https://alok-anand-ror.blogspot.com/2014/04/ruby-join-array-elements-with-single.html
这篇文章介绍了在 Ruby 编程语言中如何使用单个分隔符将数组元素连接起来。require "fcm"
def create_vibe(user)
@vibe = user.vibes.new(content: @content, picture: @picture, video: @video, isvideofile: @isvideofile, video_thumbnail: @video_thumbnail, source: @source, background_color: @background_color)
@followed = user.followers
if @followed.present?
@registration = @followed.map { |s| s.registration_id }
end
if @vibe.save
fcm = FCM.new("") # set your FCM_SERVER_KEY
options = {
data: {
notification_type: 1,
title: "#{@vibe.user.username} " "has posted a new Vibe",
body: "#{@vibe.content}",
user_data: {
vibe_id: @vibe.id,
user_id: @vibe.user.id,
background_color: @background_color,
},
},
}
response = fcm.send(@registration, options)
puts response
render :status => 200,
:json => { :success => true,
:info => "Vibe posted successfully",
:vibe_info => {
:content => @content,
:picture => @picture,
:video => @video,
:video_thumbnail => @video_thumbnail,
:isvideofile => @isvideofile,
:source => @source,
:fcm => options,
} }
else
render :status => 200, :json => { :success => false, :result => "Vibe can't be blank" }
end
end
to_sentence
只存在于 ActiveSupport 中的 Rails 中。 - Linuxiosarray.to_sentence
默认会包含牛津逗号。如果想要排除牛津逗号,可以使用array.to_sentence(:last_word_connector => " and ")
。 - niiru