Skip to content

Instantly share code, notes, and snippets.

@reu
Created September 8, 2015 15:55
Show Gist options
  • Save reu/6bab653edc844be2f110 to your computer and use it in GitHub Desktop.
Save reu/6bab653edc844be2f110 to your computer and use it in GitHub Desktop.
Scala underscore in Ruby

Scala's Undersore in Ruby

Yeah, Ruby is awesome:

# Without underscore
[1, 2, 3].map { |i| i + 1 }
[{ name: "Sasha" }, { name: "Tori" }].map { |actress| actress[:name] }

# With underscore
[1, 2, 3].map(&_ + 1)
[{ name: "Sasha" }, { name: "Tori" }].map(&_[:name])
class Underscore < BasicObject
def initialize
@calls = []
end
def method_missing(name, *args, &block)
@calls << [name, args, block]
self
end
def to_proc
-> (object) do
@calls.reduce(object) do |obj, (method, args, block)|
obj.public_send(method, *args, &block)
end
end
end
end
module Kernel
def _
Underscore.new
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment