Pergunta

Is there a way to simplify the following code?

filenames is a list of filenames (strings), e.g. ["foo.txt", "bar.c", "baz.yaml"]

filenames.map { |f| File.size(f) }

Is there any way to turn "File.size" into a proc or block? For methods on existing objects, I can do &:method. Is there something analogous for module level methods?

Foi útil?

Solução

You can use Object#method(method_name):

filenames.map(&File.method(:size))

Outras dicas

filesize = proc { |f| File.size(f) }
filenames.map(&filesize)

Stdlib's Pathname provides a more object oriented approach to files and directories. Maybe there's a way to refactor your filelist, e.g. instead of:

filenames = Dir.entries(".")
filenames.map { |f| File.size(f) }

you would use:

require 'pathname'
filenames = Pathname.new(".").entries
filenames.map(&:size)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top