How to turn a Ruby method into a block?

2019-02-04 08:14发布

问题:

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?

回答1:

You can use Object#method(method_name):

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


回答2:

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


回答3:

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)