How to turn a Ruby method into a block?

会有一股神秘感。 提交于 2019-11-30 06:38:19

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!