73

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"

7 Answers 7

133

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!

Sign up to request clarification or add additional context in comments.

9 Comments

out of curiosity can it put the Oxford comma in there too?
No, no it wont. Join won't give him quotes.
And just a note, to_sentence only exists in Rails from ActiveSupport.
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 ")
to_sentence is very useful, had no idea that existed!
|
89
["10", "20", "50","99"].map(&:inspect).join(', ') # => '"10", "20", "50", "99"'

6 Comments

map{|v| v.to_s.inspect} would handle both integer values and strings.
What happens when array elements contain "?
["10", ''].map(&:inspect).join(', ') # => '"10", ""'
I'd fail this in a code review. inspect is not intended to be used in this way.
@Linuxios has the correct answer, IMHO. Another variation: arr.map {|a| %Q("#{a}")}.join(", ")
|
19

Here:

array.map {|str| "\"#{str}\""}.join(',')

8 Comments

i got this output => "\"10\",\"20\",\"50\",\"99\""
That output is correct. The backslashes merely indicate that it's a literal quote, not a syntax quote.
@ali: that is the correct output. the is the escape character so \" stands for the character " whereas the simple " at the start and end is the string delimiter. You are probably printing the result with p x which is equivalent to puts x.inspect, try puts x instead
What happens when array elements contain "?
@dbenhur: Then you get this string: """.
|
11

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.

2 Comments

I think he just wants that string representation, not full out CSV.
it's nice for generating a String of an array which then again can be exported as on field of an CSV amongst other values
5

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

So

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

1 Comment

.to_sentence is nice, but it doesn't provide the requested output.
4

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.