Skip to content

Instantly share code, notes, and snippets.

@sw17ch
Created August 9, 2013 15:44
Show Gist options
  • Save sw17ch/6194673 to your computer and use it in GitHub Desktop.
Save sw17ch/6194673 to your computer and use it in GitHub Desktop.
# 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})
@sw17ch
Copy link
Author

sw17ch commented Aug 9, 2013

A more-fair formatting of the last example:

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