Skip to content

Instantly share code, notes, and snippets.

@cupakromer
Created July 16, 2014 18:21
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 cupakromer/ad3619347b4de978e9fa to your computer and use it in GitHub Desktop.
Save cupakromer/ad3619347b4de978e9fa to your computer and use it in GitHub Desktop.
Strange Ruby issue
# As far as I was aware, symbol-to-proc was supposed to be roughly equivalent to:
#
# Proc.new { |v| v.send(self) }
#
# However, the following produces very odd results. Why?!?
[[3, 4], [5, 6], [3, 4], [5, 6]].each_with_index.map(&:first)
# => [[], [5], [3, 4], [5, 6]]
[[3, 4], [5, 6], [3, 4], [5, 6]].each_with_index.map{ |x| x.first }
# => [3, 5, 3, 5]
[[3, 4], [5, 6], [3, 4], [5, 6]].each_with_index.map{ |*x| x.first }
# => [[3, 4], [5, 6], [3, 4], [5, 6]]
@cupakromer
Copy link
Author

This explains it: http://www.monadzoo.com/blog/2013/08/12/ruby-symbol-to-proc-is-a-lambadass/

Though I'm surprised this is how it actually works :-/

The proc created is really more akin to:

class Symbol
  def to_proc
    Proc.new{ |*args| args.shift.__send__(self, *args) }
  end
end

Which does produce the odd results! 😲

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment