I have this code
File.open(file_name, 'r') { |file| file.read }
but Rubocop is warning:
Offenses:
Style/SymbolProc: Pass
&:read
as argument toopen
instead of a block.
How do you do this?
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.
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.
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