【问题标题】:Is there a more concise way to call an outside method on a map in Ruby? [duplicate]有没有更简洁的方法在 Ruby 中的地图上调用外部方法? [复制]
【发布时间】:2013-09-19 22:22:23
【问题描述】:

有更简洁的方法吗?

# Given a directory containing subdirectories: foo, bar
targets = ['./foo', './bar', './free']
targets.map{ |d| Dir.exists? d }
# => [ true, true, false ]

我希望能够做一些类似于 proc 调用的事情......感觉更干净:

# targets.map( Dir.exists? )

【问题讨论】:

    标签: ruby enumerable proc


    【解决方案1】:

    是的,可以这样,但不利于性能(见帖子: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.
    

    【讨论】:

    • 您所说的“无点”究竟是什么意思? :)
    • 这太棒了。你能解释一下这个过程(不是双关语)吗?令人着迷!
    • 我个人认为原版读起来更好(到目前为止)。但最好有不止一种做事的方式。
    • 刚刚做了。优秀的信息。希望我能不止一次回答:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    相关资源
    最近更新 更多