Skip to content

Instantly share code, notes, and snippets.

@Jacke
Last active December 19, 2015 11:09
Show Gist options
  • Select an option

  • Save Jacke/5945362 to your computer and use it in GitHub Desktop.

Select an option

Save Jacke/5945362 to your computer and use it in GitHub Desktop.
Magic with &:symbol and &block
class Translator
def speak &language # Proc.new { |obj| obj.send(:method) }
language.call(self) # self make obj so it convert to self.send(:method)
# Proc.new { |obj| obj.send(method) } .call(self)
end
protected
def french
'bon jour'
end
def spanish
'hola'
end
def turkey
'gobble'
end
def method_missing *args
'awkward silence'
end
end
irb(main):002:0> translator = Translator.new
=> #
irb(main):003:0> translator.speak(&:spanish)
=> «hola»
irb(main):004:0> translator.speak(&:turkey)
=> «gobble»
irb(main):005:0> translator.speak(&:italian)
=> «awkward silence»
class Symbol
def to_proc
Proc.new { |*args| args.shift.__send__(self, *args) }
end
end
class Symbol
def to_proc
Proc.new { |obj| obj.send self }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment