Created
January 7, 2012 23:34
-
-
Save sgrove/1576485 to your computer and use it in GitHub Desktop.
optional multiple-return values in ruby
This file contains hidden or 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
# Starts out like this: | |
def parse_tld(url) | |
# do some stuff, get top_level_domain | |
return top_level_domain | |
end | |
# perfect | |
tld = parse_tld("example.gobushido.com") # gobushido.com | |
# ... | |
# Later, I *may* want both the tld and the subdomains | |
# 1.) I can change parse_tld to return a hash | |
# {:tld => '...', :subdomain => '...'} | |
# but I'll need to change all the invocations of parse_tld. | |
# Also, I generally don't need it, but I sometimes I might | |
# 2.) Return an array so we can do things like tld = parse_tld(url).first, or tld, subdomain = parse_tld(url) | |
# But again, I'll have to change the invocations for some information I'll only need every now and then | |
# 3.) Create a separate function (which is the route I chose) that returns just the subdomain. But now I need two function calls to get the same information, and the logic is essentially the same. | |
# 2.) Alternative syntax, similar to first, last = [], except that | |
# it only returns the first item if there's only one receiver: | |
def parse_tld(url) | |
# do some stuff, get top_level_domain and url_subdomain | |
multiple_return top_level_domain, url_subdomain | |
end | |
tld = parse_tld("example.gobushido.com") # gobushido.com | |
tld, subdomain = parse_tld("example.gobushido.com") # tld => gobushido.com, subdomain => example |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment