72

I have an array:

array = ["10", "20", "50", "99"]

And I want to convert it into a simple comma-separated string list like this:

"10", "20", "50", "99"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kashiftufail
  • 10,815
  • 11
  • 45
  • 79

7 Answers7

130

array.join(',') will almost do what you want; it will not retain the quotes around the values nor the spaces after.

For retaining quotes and spaces: array.map{|item| %Q{"#{item}"}}.join(', ') This will print "\"10\", \"20\", \"50\", \"99\"". The escaped quotes are necessary assuming the question does in fact call for a single string.

Documentation on the %Q: string literals.

You could use inspect as suggested in another answer, I'd say that's personal preference. I wouldn't, go look at the source code for that and choose for yourself.

Useful aside: array.to_sentence will give you a "1, 2, 3 and 4" style output, which can be nice!

Matt
  • 13,948
  • 6
  • 44
  • 68
  • out of curiosity can it put the Oxford comma in there too? – eds Jul 03 '12 at 15:13
  • 5
    No, no it wont. Join won't give him quotes. – Linuxios Jul 03 '12 at 15:14
  • 7
    And just a note, `to_sentence` only exists in Rails from ActiveSupport. – Linuxios Jul 03 '12 at 15:15
  • eds, no but this fella had a great anser for that :) http://stackoverflow.com/questions/6737299/create-a-human-readable-list-with-and-inserted-before-the-last-element-from-a – Matt Jul 03 '12 at 15:15
  • 13
    Just tested this in rails 3.2.5. `array.to_sentence` will include an oxford comma by default. To exclude the oxford comma, you can use `array.to_sentence(:last_word_connector => " and ")` – niiru Jul 03 '12 at 16:20
  • 2
    to_sentence is very useful, had no idea that existed! – bcb Oct 10 '13 at 14:58
  • @niiru thank you so much. Excluding Oxford comma was exactly what I needed :) – Evolve May 21 '14 at 04:36
  • Your answer doesn't answer the question. With your `array.join(",")` it outputs `"10, 20, 50, 99"` instead of `"10", "20", "50", "99"` – Rahul Dess Nov 09 '17 at 23:19
  • @RahulDess Thanks Rahul, I have updated the answer to be more accurate. – Matt Nov 10 '17 at 15:06
89
["10", "20", "50","99"].map(&:inspect).join(', ') # => '"10", "20", "50", "99"'
sczizzo
  • 3,196
  • 20
  • 28
19

Here:

array.map {|str| "\"#{str}\""}.join(',')
Linuxios
  • 34,849
  • 13
  • 91
  • 116
10

Several answers have offered solutions using #map, #inspect, #join. All of them fail to get certain details of CSV encoding correct for edge cases involving embedded commas and/or string delimiters in the elements.

It's probably a better idea to use the stdlib class CSV then to roll your own.

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

The map.join solutions are sufficient if this encoding doesn't need to care about embedded delimiters, or is intended for some internal representation only, but they will fail if generating data for exchange with other programs that expect Comma Separated Values (CSV) as a generally understood representation.

dbenhur
  • 20,008
  • 4
  • 48
  • 45
5

The simplest solution is to use the built in ".to_sentence" method.

So

["fred", "john", "amy"].to_sentence outputs "fred, john, and amy"

Michael Taylor
  • 121
  • 2
  • 6
3

This is a slightly alternative solution, particularly handy if you need to convert an array with double quoted strings to a single quoted list (for say SQL queries):

"'#{["John Oliver", "Sam Tom"].join("','")}'"

to

'John Oliver', 'Sam Tom'

Attribution: https://alok-anand-ror.blogspot.com/2014/04/ruby-join-array-elements-with-single.html

Linearza
  • 41
  • 1
0

This is how you can send push notifications using FCM for Android devices. Assuming you want notify followers when ever a user posts something on their status this is how you do it. This is done in Rails 5.2.6 for Rest Apis--- But still you can use the same for web push notifications. This is for sending to many devices with registration_ids to target followers with notifications. Gem : fcm in your controller:

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
rmlockerd
  • 3,776
  • 2
  • 15
  • 25