1

I'm new to html.erb files and I didn't find an answer to my problem. I have array of names and I'm trying to print them in a paragraph tag <p> in one line with ',' like that:

name1, name2, name3

But instead I get this:

name1,
name2,

This is the code:

<% @names_array.each do |name| %>
  <p class="center"><%= name %>,</p>
<% end %>
1
  • 1
    since you're new, you'd probably want to read up on html elements because your issue can be fixed in a lot of ways, eg using span instead of p, or changing the styling of p to display:inline. w3schools.com/tags/tag_p.asp Also google for block vs inline html elements. Commented Nov 27, 2018 at 15:32

2 Answers 2

4

You can use Active Support's to_sentence method. Example:

names = ['name1', 'name2', 'name3']

irb(main):001:0> names = ['name1', 'name2', 'name3']
=> ["name1", "name2", "name3"]

irb(main):002:0> names.to_sentence
=> "name1, name2 and name3"

You can modify the last connector passing a word option:

irb(main):003:0> names.to_sentence(last_word_connector: ', ')
=> "name1, name2, name3"

Check the documentation

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

Comments

3

Doesn't something like this work?, just join them, leaving them inside the paragraph tag:

<p class="center">
  <%= @names_array.join(', ') %>
</p>

2 Comments

it worked but I have a ',' at the end like that: name1, name2, name3, and I don't want the last ',' how can I remove it through code?
@OfirSasson if the code above leaves an empty comma at the end, it means that your last name is either an empty string ("") or a nil.

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.