Last active
August 29, 2015 14:03
-
-
Save tjmcewan/a7e4feb2976a93a5eef9 to your computer and use it in GitHub Desktop.
I dunno...
This file contains hidden or 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
# http://stackoverflow.com/a/19323467/320438 | |
def plusone(x) | |
x + 1 | |
end | |
[1,2,3].map(&:plusone) |
This file contains hidden or 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
~$ ruby -v *[master] | |
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0] | |
~$ irb *[master] | |
irb(main):001:0> def plusone(x) | |
irb(main):002:1> x + 1 | |
irb(main):003:1> end | |
=> :plusone | |
irb(main):004:0> | |
irb(main):005:0* [1,2,3].map(&:plusone) | |
NoMethodError: private method `plusone' called for 1:Fixnum | |
from (irb):5:in `map' | |
from (irb):5 | |
from /Users/tim/.rubies/ruby-2.1.2/bin/irb:11:in `<main>' | |
irb(main):006:0> |
This file contains hidden or 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
~$ ruby -v *[master] | |
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0] | |
~$ pry *[master] | |
[1] pry(main)> def plusone(x) | |
[1] pry(main)* x + 1 | |
[1] pry(main)* end | |
=> :plusone | |
[2] pry(main)> | |
[3] pry(main)> [1,2,3].map(&:plusone) | |
ArgumentError: wrong number of arguments (0 for 1) | |
from (pry):1:in `plusone' | |
[4] pry(main)> |
@tjmcewan: You can't use the :method.to_proc
/ &:method
shortcut; you need to spell it out in the block a la [1,2,3].map {|a| foo(a) }
.
(And then cry yourself to sleep.)
@damncabbage or use a lambda plusone = ->(x) { x + 1 }
and [1,2,3].map(&plusone)
@damncabbage is almost right.
irb(main):005:0> [1,2,3].map(&method(:plusone))
=> [2, 3, 4]
Better:
> [1,2,3].map(&"1".method(:foo))
=> [2, 3, 4]
... quiet sobbing
> def foo(x); x + 1; end
=> nil
> method(:foo).owner
=> Object
> 1.method(:foo).owner
=> Object
> 1.class.ancestors
=> [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]
# WELL HELLO, OBJECT.
Well, that solves that mystery.
class Numeric
def plusone
self + 1
end
end
[1,2,3].map(&:plusone)
#=> [2,3,4]
Sorry guys this is all my fault
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@damncabbage I think that's exactly my problem - I was trying to write simple functions I could just map...