Passing a class method as a block to map in ruby

时间:2018-03-08 22:12:14

标签: ruby

I'm having what's probably a silly problem but I can't for the life of me find anything about whether this can or can't be done.

Basically I'm aware that calling array.each do(&method) converts the method into a proc and calls it with each yielded value. The issue I'm having is trying to do the same with a class method.

I've written a Card class and want to parse a string with something like this.

%w{4S 5D 9H 1C 3S}.map(&Card.safe_parse)

I've tried

.map(Card.method(:safe_parse).to_proc) 

and

.map(&Card.method(:safe_parse)) 

but nothing is working. Obviously it works with .map { |x| Card.safe_parse x } but it feels like there's a cleverer way I'm not seeing and I'm trying to better understand ruby blocks.

Thanks!

1 个答案:

答案 0 :(得分:2)

漫长的方式是最传统的,但简短的方法是你的最后一个例子:

%w{4S 5D 9H 1C 3S}.map(&Card.method(:safe_parse))

这仅适用于safe_parse是模块方法,而不是mixin方法,或者换句话说,您已将其定义为self.safe_parse或在extend self结束时执行instance_method模块。

据我所知,不可能直接在mixin方法上使用compileSdkVersion 'android-P' targetSdkVersion 'P' ,因为它们缺少实例上下文。