有没有更简洁的方法来调用 Ruby 地图上的外部方法? [英] Is there a more concise way to call an outside method on a map in Ruby?

查看:55
本文介绍了有没有更简洁的方法来调用 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.

这篇关于有没有更简洁的方法来调用 Ruby 地图上的外部方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆