Skip to content

Instantly share code, notes, and snippets.

@ampledata
Created April 11, 2012 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ampledata/2361481 to your computer and use it in GitHub Desktop.
Save ampledata/2361481 to your computer and use it in GitHub Desktop.
Conditional String?
#!/usr/bin/env ruby
# I've encountered this pattern in every language I've used:
#
# 1. Given a list of items.
# 2. I want to convert this list to a string.
# 3. Where the items are separated by a comma.
# 4. The last item should not end with a comma.
#
# This is what I'm using, but I feel there's a better way:
hosts = ['taco', 'burrito']
host_list = ''
unless hosts.size == 1
host_list << "#{hosts.pop}:80, "
end
host_list << "#{hosts.pop}:80"
puts host_list
# Will print: taco:80, burrito:80
@ampledata
Copy link
Author

The solution: hosts.join(':80, ') + ':80'. Thanks all!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment