Marry Jane
Marry Jane

Reputation: 71

How to get rid of the unwanted commas

I am trying to display which moderators are currently in the room. This is what I did:

puts m.roster.keys.map { |v| "Mods in the room are: #{if m.roster[v].x[0].role.to_s.include?('moderator') then v end}" }.join(", ")

The result is:

Mods in the room are: , , User3, User4, , , , , , , User11, , User13

Are there any ways to get rid of those unwanted commas but retain commas that separate each like the following?

Mods in the room are: User3, User4, User11, User 13

Upvotes: 1

Views: 63

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

I don't follow your code, but you can modify your erroneous result as follows.

str = "Mods in the room are: , , User3, User4, , , , , , , User11, , User13"

first, *rest = str.split /(?:\s*,+)+/
  #=> ["Mods in the room are:", " User3", " User4", " User11", " User13"] 
"%s %s" % [first, rest.join(', ').lstrip]
  #=> "Mods in the room are: User3,  User4,  User11,  User13" 

Upvotes: 1

Michael Gaskill
Michael Gaskill

Reputation: 8042

Something like this might be what you're looking for:

puts "Mods in the room are: #{m.roster.select {|k,v| v.x[0].role.to_s.include?('moderator') }.keys.join(", ")}"

I believe that will give you the list of moderators.

Upvotes: 1

Related Questions