Setting the contents of a file to a variable?

Ok so…
Ok… so I have file1 and it contains a number
and I want file2 to tell me what that number is
file2 would be something like

class Tell
def get_num(file = “file1.txt”)
num = contents of file1
$num = num
end
def tell_num
puts “The number in file1 is #{$num}.”
end
end

What do I put instead of “contents of file1”
Or some completely new code that does the same thing.

Stefan Codrescu wrote:

def tell_num
puts “The number in file1 is #{$num}.”
end
end

What do I put instead of “contents of file1”
Or some completely new code that does the same thing.

File.read file

You probably also want $num to be @num instead (that is, an instance
variable rather than a global variable).

-Justin

ok, thanks ill try that but i also found
file = File.open(“guess.txt”)
$guess = file.gets
which works for what im using it for.

Stefan Codrescu wrote:

ok, thanks ill try that but i also found
file = File.open(“guess.txt”)
$guess = file.gets
which works for what im using it for.

BTW, you forgot to close the file. Although that doesn’t matter in a
short-lived script, there is a way of avoiding this problem:

File.open(“guess.txt”) do |file|
$guess = file.gets
end

This opens the file, runs the block, and then closes the file (even if
the block aborted with an exception rather than completing successfully)

BTW, local variables which are first seen within a block are private to
that block, so if you want do use a local variable do this:

guess = nil
File.open(“guess.txt”) do |file|
guess = file.gets
end
… now ‘guess’ contains the result of reading the 1st line of file

Brian C. wrote:

BTW, local variables which are first seen within a block are private to
that block, so if you want do use a local variable do this:

guess = nil
File.open(“guess.txt”) do |file|
guess = file.gets
end
… now ‘guess’ contains the result of reading the 1st line of file

Or even this:

guess = File.open(“guess.txt”) do |file|
file.gets
end

Maybe even this (Symbol#to_proc implementation/Ruby 1.9 required):

guess = File.open(“guess.txt”, &:gets)

-Matthias

Brian C. schrieb:

$guess = file.gets
guess = file.gets

end
… now ‘guess’ contains the result of reading the 1st line of file
if you just need the content, use File.read, if you need the lines in an
Array use File.readlines

Matthias R. schrieb:

Or even this:

did you read my post? why should we use a construct with a block if
there are several methods to do this directly?

badboy wrote:

did you read my post? why should we use a construct with a block if
there are several methods to do this directly?

Because the block way is the Ruby way, besides it’s much more efficient
it does open, read and close in one short command! Beside it its
elegance it also has a pedagogical value, namely, it highlights and
exposes the use of Ruby 1.9 usage of Symbol class to_proc strategy. So
all I can say is: Matthias, excellent contribution to this thread, very
good job.

Perhaps only a comment that even reading multi-line file into a variable
sometimes can be useful with:

guess = File.open(“zorba.data”, &:readlines)

Clearly the old way in comparison to the the block is more like the
spaghetti code!

Torli

badboy wrote:

Matthias R. schrieb:

Or even this:

did you read my post? why should we use a construct with a block if
there are several methods to do this directly?

If you just want the first line of a file (and that’s what I was
specifically refering to) then reading in the whole file might not be
the best idea.

-Matthias

2009/3/9 Torli B. [email protected]:

badboy wrote:

did you read my post? why should we use a construct with a block if
there are several methods to do this directly?

Because the block way is the Ruby way, besides it’s much more efficient
it does open, read and close in one short command! Beside it its
elegance it also has a pedagogical value, namely, it highlights and
exposes the use of Ruby 1.9 usage of Symbol class to_proc strategy. So
all I can say is: Matthias, excellent contribution to this thread, very
good job.

Frankly, I believe you haven’t properly read badboy’s posting. I’ll
show his code below.

Perhaps only a comment that even reading multi-line file into a variable
sometimes can be useful with:

guess = File.open(“zorba.data”, &:readlines)

Clearly the old way in comparison to the the block is more like the
spaghetti code!

Like these?

17:45:12 tmp$ cat >| x <<EOF

123
456
EOF
17:45:23 tmp$ cat x
123
456
17:45:25 tmp$ allruby -e ‘p File.read(“x”), File.readlines(“x”)’
ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin]
“123\n456\n”
[“123\n”, “456\n”]
ruby 1.9.1p0 (2009-01-30 revision 21907) [i386-cygwin]
“123\n456\n”
[“123\n”, “456\n”]
17:45:55 tmp$

Very spaghetti indeed.

Cheers

robert

PS: This posting contains traces of irony. Please handle with care.

2009/3/9 Torli B. [email protected]:

Robert K. wrote:

tmp$ cat >| x <<EOF

All programming languages can be abused. This does not make the abuser a
hero!

That was just a tool to create the file. I could have also used a
text editor, echo commands or whatever.

PS: whose main message is in the “ps” addendum must have missed the
point totally!

I am sorry, but I believe you are missing the point. The main message
was in this line

17:45:25 tmp$ allruby -e ‘p File.read(“x”), File.readlines(“x”)’

In other words: with methods like File.read and File.readlines which
can be as simply used as demonstrated above there is simply no point
in using any of the presented block forms - especially not
File.open(“zorba.data”, &:readlines) which does not work in pre 1.9
versions - for reading a complete file into a single variable (either
as String or as Array). These methods are as safe with regard to file
handle closing as the block form of File.open (which I usually
advocate when appropriate). That is the point that badboy tried to
make.

Having said that, the simplest and most efficient form to read a
number from a file that does not contain much more are probably these

  • depending on whether a float or an integer is to be read:

num = File.read(“file1.txt”).to_i
num = File.read(“file1.txt”).to_f

If file contents are not guaranteed and input verification needs to be
done then you can do this as a first line of defense

num = Integer(File.read(“file1.txt”))
num = Float(File.read(“file1.txt”))

Of course, arbitrary more complex parsing schemes can be devised.

Cheers

robert

Oh, I do not think I am the one missing anything. I challenge you to
first explain your sarcastic concoction “tmp$ cat >| x <<EOF” which I
claim is an exhibitionist’s exaggeration of “apparent” Unix/Perl - Ruby
like gibberish. The point I was making was that a succinct Ruby1.9’s way
of using a Symbol class to_proc strategy, as Matthias showed us, is
superior to anything else discussed here. You two, Robert and especially
badboy, complained about using a block when a simpler, and by most from
M$ emerging Ruby programmers better understood, spaghetti code exists.

If anybody should take seriously what you, Robert and badboy, are
saying regular expressions, and indeed Unix shell and all its cryptic,
and powerful paraphernalia are pure garbage. And since today’s mouse
pushing computer “professionals” do not see Ruby until they loose their
“secure” jobs in M$ dominated environments, it looks that such opinions
as yours are a credible ones. The truth is, that those who write
gibberish like: “tmp$ cat >| x <<EOF” are appealing to the ignorant
public who can not discern a fake from a true argument, and most likely
have not had a chance to rise above that ignorance themselves.

Now this argument has turned into pseudo serious technical discussion,
which is only obfuscating the real issue here and indeed is missing a
point.

Cheers, Torli

Robert K. wrote:

tmp$ cat >| x <<EOF

All programming languages can be abused. This does not make the abuser a
hero!

PS: whose main message is in the “ps” addendum must have missed the
point totally!

Torli

Torli B. wrote:

I challenge you to
first explain your sarcastic concoction “tmp$ cat >| x <<EOF” which I
claim is an exhibitionist’s exaggeration of “apparent” Unix/Perl - Ruby
like gibberish.

It’s actually a pretty typical command line, and to Robert’s credit,
very concise.

tmp$ is a shell prompt meaning, by convention, that the shell is a
Bourne derivative, and that its current working directory is called tmp.

cat copies its standard input to its standard output.

| means tells the shell to redirect cat’s output to a file, and to
overwrite the file if it already exists.

x is the name of the output file.

<<EOF means tells the shell to keep reading input for cat, until a line
containing just the letters EOF is encountered. EOF is a conventional
abbreviation for “end of file.”

This is one of those rare moments where RTFM really does apply.

Jeff S. wrote:

This is one of those rare moments where RTFM really does apply.

Yet another defender of obfuscation and deception with fabricated
gibberish, only to glorify some minuscule know-how with RTFM phrase.

The code Robert wrote is Unix shell code and has nothing to do with Ruby
discussion here. Besides, it should be mentioned that it is shell and on
top of that if written properly for a discussion like this should look
like the following:

$ cat >|x <<EOF

123
EOF
cat x
$ 123

and not like

Robert K. wrote:

17:45:12 tmp$ cat >| x <<EOF

123
456
EOF
17:45:23 tmp$ cat x
123
456
17:45:25 tmp$ allruby -e ‘p File.read(“x”), File.readlines(“x”)’
ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin]
“123\n456\n”
[“123\n”, “456\n”]
ruby 1.9.1p0 (2009-01-30 revision 21907) [i386-cygwin]
“123\n456\n”
[“123\n”, “456\n”]
17:45:55 tmp$

The intention of the above clearly is to show a sarcastic opinion of a
frustrated mouse pusher, who has to bury his point in garbage to confuse
the audience. I asked him to explain what he wrote and the answer to the
above gibberish is very simple:

Unix shell

$ cat >|x <<EOF

123
EOF
cat x
$ 123

On Mar 10, 2009, at 1:14 PM, Torli B. wrote:

The intention of the above clearly is to show a sarcastic opinion of a
frustrated mouse pusher, …

“…frustrated mouse pusher…” I will have to remeber that one! :slight_smile:

Cheers–

Charles

Charles J.
Advanced Computing Center for Research and Education
Vanderbilt University