Is there a more concise way to call an outside method on a map in Ruby? [duplicate]

瘦欲@ 提交于 2019-11-29 22:56:42

问题


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 ]

I'd love to be able to do something similar to proc calls... it feels cleaner:

# targets.map( Dir.exists? )

回答1:


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.


来源:https://stackoverflow.com/questions/18816654/is-there-a-more-concise-way-to-call-an-outside-method-on-a-map-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!