How to turn a Ruby method into a block?

≡放荡痞女 提交于 2019-11-29 06:20:37

问题


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)


来源:https://stackoverflow.com/questions/18252630/how-to-turn-a-ruby-method-into-a-block

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