Rails Join a List of Strings with Commas and "And" Before the Last

Rails join a list of strings with commas and and before the last

Yeah to_sentence ought to work nicely.

http://apidock.com/rails/Array/to_sentence

Joining array of strings into a quoted comma-separated list

I would use map and join:

arr = ["one", "two", "three"]

arr
.map { |e| "`#{e}`" }
.join(', ')

You could even put it on a single line:

arr.map { |e| "`#{e}`" }.join(', ')

Now, I'm not entirely sure of this, but it looks like you might be using this to perhaps quote parameters for an SQL query? If you are, then please don't do it like this, but use a proper SQL escaping function or parameterized queries.


In response to the confirmation that you're using this for an SQL query, a better way would be to use (assuming you're using sqlite3-ruby):

db = SQLite3::Database.new 'my_database.sqlite3'
arr = ["one", "two", "three"]

db.execute('select * from foo where a=? and b=? and c=?', arr) do |row|
p row
end

This will make sure it always works. Adding backticks may seem like a good idea at first, but:

  • There are ways to work around this and do an SQL injection attack. This is bad and allows anyone to read or destroy data.
  • Even if it's just for personal use, it's good to do it the "proper way", since sooner or later you'll run into the problem that your data has a ` or some other special character you didn't think of, at which point your program breaks.

Create a human-readable list with and inserted before the last element from a ruby list

Try: [list[0...-1].join(", "), list.last].join(", and ").

Edit: Rails has the method you were probably looking for, called to_sentence.

In case you do not have Rails or do not wish to depend on Rails, open Array class and include the above method, like:

class Array
def join_all(join_with = ", ", connector = "and", last_comma = false)
return self.to_s if self.empty? || self.size==1
connector = join_with+connector if last_comma
[list[0...-1].join(join_with), list.last].join(connector)
end
end

Easy way to separate strings in an array with commas in Rails with and before last string

Rails has a method to_sentence:

[1,2,3].to_sentence
# => "1, 2, and 3"

Remove last comma from serialized array.join(', ')?

It's not clear why the array has an empty string as the last element, but it's easy to skip it:

self.committed[0..-2].to_sentence.titleize

Or:

self.committed.reject(&:blank?).to_sentence.titleize

The latter will skip all blank elements, whereas the former will skip the last element regardless of its content.

If you want to individually capitalize the words before calling to_sentence (to avoid "and" being capitalized), just use map:

self.committed[0..-2].map(&:titleize).to_sentence

Array join with commas, only when element is not nil

Example:

["", nil, "test word", 5, 7, nil, "", nil, "", 7, 6, ""] => "test word, 5, 7, 7, 6"

Edit: Please note that the first method here requires Ruby on Rails. Use the second method for a Ruby-only solution

You can try this to remove both nil and empty strings "" and then join with commas (It removes all nil values with compact, then it does split on "" to create a two-dimensional array where any "" elements in the first array are just empty arrays in the new 2D array, then it does flatten which turns the 2D array back into a normal array but with all the empty arrays removed, and finally it does the join(", ") on this array):

> array.compact.split("").flatten.join(", ")

array = ["", nil, "test word", 5, 7, nil, "", nil, "", 7, 6, ""]

array.compact => ["", "test word", 5, 7, "", "", 7, 6, ""].split("") => [[], ["test word", 5, 7], [], [7, 6], []].flatten => ["test word", 5, 7, 7, 6].join(", ") => "test word, 5, 7, 7, 6"

Edit: Another way would be:

> array.reject(&:blank?).join(", ")

array = ["", nil, "test word", 5, 7, nil, "", nil, "", 7, 6, ""]

array.reject(&:blank?) => ["test word", 5, 7, 7, 6].join(", ") => "test word, 5, 7, 7, 6"

How do I convert an array of strings into a comma-separated string?

["10", "20", "50","99"].map(&:inspect).join(', ') # => '"10", "20", "50", "99"'

Rails group and join with a comma

You are not comparing, what you think you are comparing:

<%= "," unless open_hours == open_hours.last %>

You are comparing the entire array open_hours to the last element of the same array open_hours.last

You probably wanted to compare the current opening time to check if it was the last element:

<%= "," unless open == open_hours.last %>

But anyway, there is a much nicer way to do this, if you have an array you can just join it together like this:

<%= open_hours.map do |open| %>
<% I18n.l open.opens, :format => :custom %> -
<% I18n.l open.closes, :format => :custom %>
<% end.join(', ') %>

And probably it would be better to write some helper or some model method for this.



Related Topics



Leave a reply



Submit