Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass &:read as argument to File.open as indicated by Rubocop

Tags:

ruby

rubocop

I have this code

File.open(file_name, 'r') { |file| file.read }

but Rubocop is warning:

Offenses:

Style/SymbolProc: Pass &:read as argument to open instead of a block.

How do you do this?

like image 647
Obromios Avatar asked Jan 03 '19 03:01

Obromios


2 Answers

I just created a file named "t.txt" that contains "Hello, World\n". We can read that as follows.

File.open('t.txt', 'r', &:read)
  #=> "Hello, World\n"

Incidentally, as the default of the second argument is 'r', it suffices to write:

File.open('t.txt', &:read)

Here's another example:

"This is A Test".gsub('i', &:upcase)
  #=> "ThIs Is A Test" 

In other words, include the proc (e.g., &:read) as the last argument.

like image 160
Cary Swoveland Avatar answered Sep 21 '22 00:09

Cary Swoveland


File.open(file_name, 'r', &:read)

Rubocop wants you to use the 'symbol to proc' feature in Ruby instead of defining a complete block. This is purely stylistic, and doesn't affect the code execution. You can find it in the Rubocop style guide.

like image 23
Tom Avatar answered Sep 19 '22 00:09

Tom