Created
February 28, 2013 01:09
-
-
Save srawlins/5053352 to your computer and use it in GitHub Desktop.
Method chaining can still _be_ magical, and not have to _look_ like magic.
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
number = 1234567 | |
# Chaining methods more than once-ish is confusing; the developer has to keep | |
# in mind wtf is going on: | |
number.to_s.reverse.split(//).each_slice(3).map(&:join).join(',').reverse | |
# Commenting the state of each chain helps: | |
number.to_s. # String, e.g. "1234567" | |
reverse. # reverse it, e.g. "7654321" | |
split(//). # split on every character, e.g. ["7", "6", "5", "4", "3", "2", "1"] | |
each_slice(3). # Enumerator for every 3 elements, effectively [["7", "6", "5"], ["4", "3", "2"], ["1"]] | |
map(&:join). # map each element, x, to x.join(), e.g. ["765", "432", "1"] | |
join(','). # join those elements with commas, e.g. "765,432,1" | |
reverse # re-reverse, e.g. "1,234,567" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment