Created
August 9, 2013 15:44
-
-
Save sw17ch/6194673 to your computer and use it in GitHub Desktop.
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
# First, make the thing that I want. | |
class Object | |
# Becomes passes self to a block. The result of the | |
# operation is the result of the block rather than the | |
# original object. This allows us to transform an object | |
# in-line with a method chain without having to mix-in or | |
# add the method to any of the objects. | |
def becomes | |
yield self | |
end | |
end | |
# Make some transformation functions. | |
def as_a_string(o); o.to_s end | |
def first_half(a); a.take(a.length / 2) end | |
def second_half(a); a.drop(a.length / 2) end | |
# Some exampling: | |
# I'd prefer to do this: | |
p ["hello", "world"].becomes{|o| as_a_string(o)} | |
# Instead of this: | |
p as_a_string(["hello", "world"]) | |
# Expecially as the expression becomes bigger | |
p (1..10).to_a | |
.becomes {|x| second_half(x)} | |
.map {|x| x + 1} | |
.becomes {|x| first_half(x)} | |
# To me, the previous example reads a little easier than this. | |
p first_half(second_half((1..10).to_a).map {|x| x + 1}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A more-fair formatting of the last example: