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

StackOverflow https://stackoverflow.com/questions/18816654

  •  28-06-2022
  •  | 
  •  

Вопрос

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? )
Это было полезно?

Решение

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.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top