Skip to content

Instantly share code, notes, and snippets.

@iain
Created February 5, 2010 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iain/296165 to your computer and use it in GitHub Desktop.
Save iain/296165 to your computer and use it in GitHub Desktop.
# Without Symbol#to_proc
[1, 2, 3].map { |it| it.to_s }
[3, 4, 5].inject { |memo, it| memo * it }
# With Symbol#to_proc
[1, 2, 3].map(&:to_s)
[3, 4, 5].inject(&:*)
some_dates.map(&:strftime.with("%d-%M-%Y"))
<%= @prices.map { |price| number_to_currency(price) }.to_sentence %>
<%= @prices.map(&it.number_to_currency).to_sentence %>
class SomeClass
include ProcProxyHelper
def initialize(name, list)
@name, @list = name, list
end
def apply(value, index, seperator)
"#{@name}, #{index} #{separator} #{value}"
end
def applied_list
@list.map.with_index(&it.apply(":"))
end
end
<%= some_texts.map(&it(2).content_tag(:span, :class => "foo")).to_sentence %>
module ProcProxyHelper
def it(position = 1)
ProcProxy.new(self, position)
end
class ProcProxy
instance_methods.each { |m| undef_method(m) unless m.to_s =~ /^__|respond_to\?|method_missing/ }
def initialize(object, position = 1)
@object, @position = object, position
end
def to_proc
raise "Please specify a method to be called on the object" unless @delegation
Proc.new { |*values| @object.__send__(*@delegation[:args].dup.insert(@position, *values), &@delegation[:block]) }
end
def method_missing(*args, &block)
@delegation = { :args => args, :block => block }
self
end
end
end
class Symbol
def with(*args, &block)
@proc_arguments = { :args => args, :block => block }
self
end
def to_proc
@proc_arguments ||= {}
args = @proc_arguments[:args] || []
block = @proc_arguments[:block]
@proc_arguments = nil
Proc.new { |obj, *other| obj.send(self, *(other + args), &block) }
end
end
class Symbol
def to_proc
Proc.new { |obj, *args| obj.send(self, *args) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment