Created
July 16, 2014 18:21
-
-
Save cupakromer/ad3619347b4de978e9fa to your computer and use it in GitHub Desktop.
Strange Ruby issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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]] |
oops meant to leave that there, 2.1.2p95
*x
passes along the index too, so x.first
is the array. x
has a second argument (the index) that was left out, so x.first
is the first element in the array.
No idea what's going on with &:first
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
Just for the sake of checking: What version(s) of Ruby have you done this on?