Last active
January 5, 2017 18:37
-
-
Save princebot/530b5910afc0ac6d1ed00fa5fedde230 to your computer and use it in GitHub Desktop.
Exploring Ruby's black magic #1
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
# This Enumerator#sum example from the Ruby docs is pure black magic to me: | |
# | |
# "a\nb\nc".each_line.lazy.map(&:chomp).sum("") #=> "abc" | |
# | |
# So I’mma figure out how and why it works by implementing a version of it. | |
# Sigils are Symbol-like objects that can be converted to Procs. | |
class Sigil | |
def initialize(name) | |
@name = name | |
end | |
def to_sym | |
@name.to_sym | |
end | |
def to_proc | |
puts "self => #{self.inspect}" | |
Proc.new { |obj, args| obj.send(self.to_sym, *args) } | |
end | |
end | |
sigil = Sigil.new 'upcase' | |
block = s.to_proc | |
block.call 'a wild foo appeared!' # => "A WILD FOO APPEARED!" | |
%w(foo bar baz).map &sigil # => ["FOO", "BAR", "BAZ"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment