Skip to content

Instantly share code, notes, and snippets.

@princebot
Last active January 5, 2017 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save princebot/530b5910afc0ac6d1ed00fa5fedde230 to your computer and use it in GitHub Desktop.
Save princebot/530b5910afc0ac6d1ed00fa5fedde230 to your computer and use it in GitHub Desktop.
Exploring Ruby's black magic #1
# 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