Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a Ruby method into a block?

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?

like image 567
Martin C. Martin Avatar asked Aug 15 '13 12:08

Martin C. Martin


People also ask

How do you define a method that can accept a block as an argument Ruby?

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 .

How do Ruby blocks work?

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.

What is block given in Ruby?

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.


1 Answers

You can use Object#method(method_name):

filenames.map(&File.method(:size))
like image 188
tokland Avatar answered Oct 14 '22 17:10

tokland