我有一个数组:
array = ["10", "20", "50", "99"]
我想把它转换成这样一个简单的逗号分隔的字符串列表:
"10", "20", "50", "99"
这里:
array.map {|str| "\"#{str}\""}.join(',')
array.join(',')几乎可以满足您的需要; 它不会保留值周围的引号和后面的空格。
array.join(',')
保留引号和空格: array.map{|item| %Q{"#{item}"}}.join(', ') 这将打印 "\"10\", \"20\", \"50\", \"99\""。转义引号是必要的,假设问题实际上需要一个字符串。
array.map{|item| %Q{"#{item}"}}.join(', ')
"\"10\", \"20\", \"50\", \"99\""
关于 %Q: 字符串字面值的文件。
%Q
你使用 inspect作为 在另一个答案中暗示,我会说这是个人偏好。我不会,去看看 源代码,为自己选择。
inspect
有用的一边: array.to_sentence将给你一个“1,2,3和4”样式的输出,这可以是很好的!
array.to_sentence
["10", "20", "50","99"].map(&:inspect).join(', ') # => '"10", "20", "50", "99"'
有几个答案提供了解决方案使用 #map,#inspect,#join。它们都未能获得 CSV 编码的某些细节,这些细节适用于元素中包含内嵌逗号和/或字符串分隔符的边缘情况。
#map
#inspect
#join
也许使用 stdlib 类 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)作为通常理解的表示,那么这种解决方案就会失败。
最简单的解决方案是使用内置的“ . to _ words”方法。
那么
[“ fred”,“ john”,“ amy”]
这是一个稍微可替代的解决方案,特别是当您需要将带有双引号字符串的数组转换为单引号列表时(比如 SQL 查询) :
"'#{["John Oliver", "Sam Tom"].join("','")}'"
到
'John Oliver', 'Sam Tom'
署名: https://alok-anand-ror.blogspot.com/2014/04/ruby-join-array-elements-with-single.html
这就是为 Android 设备使用 FCM 发送推送通知的方式。 假设您希望在用户发布状态信息时通知追随者,那么您就应该这样做。这是在 Rails 5.2.6 for Rest Apis 中完成的——但是你仍然可以对 web 推送通知使用同样的方法。这是为了发送到许多具有 register _ ids 的设备,以通知目标跟随者。 宝石: fcm 在你的控制器中:
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