有没有更简洁的方法来调用 Ruby 地图上的外部方法?
问题描述:
有没有更简洁的方法来做到这一点?
Is there a more concise way of doing this?
# Given a directory containing subdirectories: foo, bar
targets = ['./foo', './bar', './free']
targets.map{ |d| Dir.exists? d }
# => [ true, true, false ]
我希望能够做一些类似于 proc 调用的事情......感觉更干净:
I'd love to be able to do something similar to proc calls... it feels cleaner:
# targets.map( Dir.exists? )
答
是的,可以这样,但不利于性能(参见帖子:&method(:method_name) 习语对 Ruby 的性能有害吗?):
Yes, possible this way, but not good for performance (see post: Is the &method(:method_name) idiom bad for perfomance in Ruby?):
targets = ['./foo', './bar', './free']
targets.map(&Dir.method(:exists?))
# => [false, false, false] #all are false,as I don't have such directories.