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?
We can explicitly accept a block in a method by adding it as an argument using an ampersand parameter (usually called &block ). Since the block is now explicit, we can use the #call method directly on the resulting object instead of relying on yield .
Ruby blocks are anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or curly braces {}. do-end is usually used for blocks that span through multiple lines while {} is used for single line blocks. Blocks can have arguments which should be defined between two pipe | characters.
Ruby blocks are little anonymous functions that can be passed into methods. Blocks are enclosed in a do / end statement or between brackets {} , and they can have multiple arguments.
You can use Object#method(method_name):
filenames.map(&File.method(:size))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With