Question

This is how I am reading my file:

raw = File.open(fname) { |f| f.read }

I thought I would take advantage of Ruby's shortcuts, such as the & operator to convert its argument to a proc. For example, one could use

nums = gets.split.map &:to_i   # get numbers from stdin

Instead of

nums = gets.split.map { |x| x.to_i }

So, I tried:

raw = File.open(fname) &:read

And I got the error:

path/to/file.rb:3:in `<main>': undefined method `&' for #<File:testing.txt> (NoMethodError)

It doesn't work with parentheses either (raw = File.open(fname)(&:read)).

How can I use this shortcut for opening a file? If I can't, then why not?

Was it helpful?

Solution

Try

raw = File.open(fname).read

Edit: The problem with this is that it doesn't close the file, as OP stated.

However this does work with ruby 1.9.3p448:

raw = File.open(fname, &:read)

This is just to demonstrate the use of the &/symbol representation of a block in ruby. As sawa points out, in actual practice one would ordinarily do:

raw = File.read(fname)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top