Skip to content

Instantly share code, notes, and snippets.

@kaspth
Created June 28, 2014 20:22
Show Gist options
  • Save kaspth/9b743ab67301530e4601 to your computer and use it in GitHub Desktop.
Save kaspth/9b743ab67301530e4601 to your computer and use it in GitHub Desktop.
# This:
class String
def to_proc
split('.').to_proc
end
end
class Array
def to_proc
lambda do |obj|
inject(obj) do |value, method|
value = value.send(method)
end
end
end
end
# Means you can do:
%w(hello world).map(&'upcase.bytes') # => [[72, 69, 76, 76, 79], [87, 79, 82, 76, 68]]
%w(hello world).map(&[:upcase, :bytes]) # => [[72, 69, 76, 76, 79], [87, 79, 82, 76, 68]]
# BONUS
# Extra silly (functional-like) implementation
class Array
def self.to_proc
lambda do |arr|
lambda do |obj|
arr.inject(obj) do |value, method|
value = value.send(method)
end
end
end
end
def to_proc
self.class.to_proc.(self)
end
end
method_chain_maker = Array.to_proc
chain_one = method_chain_maker.([:upcase, :bytes]) # Make as many chains as you want
%w(hello world).map(&chain_one) # => [[72, 69, 76, 76, 79], [87, 79, 82, 76, 68]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment