문제

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?

도움이 되었습니까?

해결책

You can use Object#method(method_name):

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

다른 팁

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top