Using "each do" to output a list, how to skip the last comma?

Viewed 52

Ruby beginner:

Outputting a list using

each do

When I print the list, It iterates the puts"," the same amount of times as the list, because, well that's what I told it to do. How to I tell it to not to put the comma the last time/skip the last comma and put a question mark instead? Sample code below:


contacts = {
    "Freddy" => {
    "phone" => 666,
    "tiktok" => "asdf",
    "instagram" => "def",
    "email" => "in.your@dreams"
  }
}
name = "Freddy"

print "We know these things about #{name}:"
    contacts[name].each do |key, value|
        print " #{key}"
        print "," 
    end
    print "?\n" 

Desired output is: We know these things about Freddy: phone, tictok, instagram, email?

not

We know these things about Freddy: phone, tictok, instagram, email,? (get rid of last comma)

3 Answers

I would be inclined to form the full string using string interpolation and then put-s it:

puts "We know know these things about %s: %s?" %
  [name, contacts[name].keys.join(', ')]

displays

We know know these things about Freddy: phone, tiktok, instagram, email? 

See Kernel#sprintf for string formatting directives.

Joining the keys with a comma would be much easier that trying to skip the last comma in an each do loop:

print contacts[name].keys().join(", ")

You could also use the * ruby sugar syntax:

print contacts[name].keys * ", "
Related