Created
April 11, 2012 19:07
-
-
Save ampledata/2361481 to your computer and use it in GitHub Desktop.
Conditional String?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The solution:
hosts.join(':80, ') + ':80'
. Thanks all!