Learn Ruby the hard way, Excercise 16: Reading and writing files

This excercise introduced, well, reading and writing stuff. Here is the code:

filename = ARGV.first

puts "We're going to erase #{filename}"
puts "If you don't want that, hit CTRL-C (^C)."
puts "If you do want that, hit RETURN."
$stdin.gets.chomp

puts "opening the file...."
target = open(filename, 'w')

puts "Truncating the file. Goodbye!"
target.truncate(0)

puts "Now we're going to ask you for three lines."

print "line 1: "
line1 = $stdin.gets.chomp
print "line 2: "
line2 = $stdin.gets.chomp
print "line 3: "
line3 = $Stdin.gets.chomp
 
puts "Now we're going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

puts "And finally, we close it."
target.close

This output the following to the consol

ex16 consol1

This excercise creates has the user input a filename into the ARGV array, the contents of ARGV are assigned to the variable target and then this files contents are erased with truncate. We then write information to target using gets. The original filename given in the command line doesn’t matter – it could have been swiss_cheese and it would still work fine.

As I hadn’t created a the text file test.txt before running the script,  the line target = open(filename, ‘w’) created it in the location where the ruby script was running from.

This excercise introduced and brushed up on the following functions:

  • close – closing a file
  • read – reading the contents of a file
  • readline – reading just one line of a text file
  • truncate – empties a file.
  • write – writes stuff to a file when you put it inside parentheses i.e target.write(“stuff”) In this excercise we used the parameter w for write only mode. This means we can write to a file but not read from it , the file pointer starts at the begining of the file and erases everything.

Study Drills

1.If you do not undertstand this script, go back through it and use command trick to get it squared away in your mind. One simple English comment above each line will help you understand or at least let you know what you need to research more.

I get this script however the comment trick is a good thing to do when you started learning ruby not long ago.  Here are the english comments for the script anayway:

ex16 study drill 2.png

2. Write a script similar to the last exercise that uses read and ARGV to read the file you just creat

ex16 reader.png
Study drill 2 code
ex 16 study drill consol
Study drill 2 consol

3. There’s too much repetition in this file, use strings, formats and escape to print out line1, line2, line3 with just one target.write() command instead of six.

Ok so I decided to cheat and not use escape sequence at all and cut out the .chomp fucntion so the string will still contain a new line / RETURN when the user enters types in the names for line1, line2 and line3

ex16 study drill 3.png

However this seemed a little sloppy so after copying someone else’s code researching another blog I discovered it could be done more succinctly as:

ex 16 study drill 3 2.png

4. Find out why we had to pass a ‘w’ as an extra parameter to open. Hint: Open tries to be safe by making you explicitly say you want to write a file.

We had to pass a ‘w’ as a parameter as by default ruby will open the file in ‘r’ mode which is read only. When I changed the open parameter to ‘r’ I got the following message:

ex16.rb:13:in 'truncate' not opened for writing <IOERROR>

Meaning Ruby can’t run truncate if the file is opened in read only mode.

5. If you open the file with ‘w’ mode, then do you really need the target.truncate()?

You do explicitly need to state ‘w’ mode in order to call truncate on the file.  However – as far as I can tell Truncate is redundant here and the author is testing us and no amount of research seems to prove to the contrary! I though that perhaps ‘w’ mode will only erase as far as you write or as far as the file pointer goes, so to test this I removed target.truncate(0) from the script and ran it with just .write in ‘w’ mode and wrote a long paragraph which saved to text.txt, then ran the script again with a very short line. Howver the file was completely erased so Truncate is not needed here!

Common Student Questions

Is the truncate() necessary with the ‘w’ parameter? (See Study drill 5)

 

 

 

 

 

 

 

 

Learn Ruby the Hard Way, Excercise 15: Reading Files

Here is the code for the excercise in it’s final form:

filename = ARGV.first

txt = open(filename)

puts "Here's your file #{filename}:"
print txt.read
txt.close

print "Type the filename again:"
file_again =$stdin.gets.chomp

txt_again = open(file_again)

print txt_again.read
text_again.close

This excercise introduced opening and reading from files uses the .open and .read functions. I also learnt that open creates a file object which the author says is not the actual contents of the file! The script above will print out:

 

ex 15 consol

Study Drills

1. Above each line write out in English what it does 
- Done:
noptepad
2. If you are not sure ask someone for help online.

– Yup – researched how gets & ARGV work together this way

3. I used the word commands here, but commands are also called functions and methods.

– That I did not know

4.Get rid of lines 8-13 where you use gets.,chomp and run the script again

– yup, it worked fine.

5. Use only gets and .chomp and try the script that way, why is one way of getting the filename better than the other?

– I tried this using lines 8-13 and deleting the rest of the scirpt. It worked fine but as far as I can see inputting from arguments from the consol is more efficient. Also you could name all the files you wanted to use up front.

6. Start irb to start the Ruby shell, and use open from the promt just like in this program.  Notice you can open files and run read on them from within irb?

Untitled.png

7.Have your script also call close() on the txt and txt_again variables. It's important to close files when your are done with them.

I had not thought to do that and assumed this would automatically be done – I will have to research this later.

Screenshot_1

 

 

 

 

 

 

Learn Ruby the Hard Way, Exercise 14: Prompting and Passing

Here is the code for excercise 14:

ex14 1.png
Excercise 14 code

This excercises was fairly straight forwards and introduced using the standard input string method , $stdin together with ARGV just to recap again, ARGV and .gets don’t work together unless you call ARGV.clear later in the script after or use $stdin.gets to get input directly from the user otherwise gets will attempt to get input straight from ARGV and crash the script….Anyway here is the code for the excercise on the consol.

ex14 2

Study Drills

1.Find out what Zork and Adventure were. Try to find copies and play them.

I researched Zork, and you can play it here and it’s frickin sweet

2.Change the promt variable to something else entirely.

I changed it to supercalifragilisticexpialidocious. It worked fine.

3.Add another argument and use it in your script, the same way you did in the previous excercise with first, second = ARGV.

I did and usaed the second argument to enter my last name which worked fine. On Line 4 I made a new variable name to save faffing around and using the #format activator every time I needed to input my full name.

ex 14 5.png
excercise 14 study drill 3

ex 14 4

4.Make sure you understand how I combined a “”” style multiline string with #{} format activator as the last print

“”” can be used to print string data to the consol over multiple lines and saves having to write puts repeatedly. The #{} is used to place a string data inside a string (I think, there is not a whole lot of info on #{} on the web.

 

Learn Ruby the Hard Way, Excercise 13: Parameters, Unpacking, Variables

This excercise introduced Argument variables which took some getting used to .

ex13 1

When you entere something into the command line you are passing arguments, so for instance when I typed “Ruby ex13.rb” into the command line, the ex13.rb part was an argument.  In this case the script ex13.rb also happens to accept arguments thanks to the bit of code on line 1 with ARGV which is an argument variable.

An argument variable holds (or contains if you will) the arguments given at the command line. On line 1 of this scipt it unpacks the arguments and assigns them to three normal variables ‘first’, ‘second’ and ‘third’.

The arguments come into the script as normal strings,  so ‘Apple’ which I typed at the command line was an argument, was then imported into the argument variable (ARGV) then unpacked and assigned to the ‘first’. This created the variable ‘Apple’ in the script.

 

ex13 2

 

Study Drills

1.Try givng fewer than three arguments to your script

Sure here you go:

ex 13 alt 1

ex 13 alt 2

2. Write a script that has fewer arguments and one that has more. Make sure you give the unpacked variables good names.

ex 13 alt 3

ex 13 alt 4

3. Combine gets.chomp with ARGV to make a script that gets more input from the user.

I a gets.chomp at the end of the last script and got the following error message when I ran it

ex13_alt_2.rb:10:in ‘gets’: No such file or director @ rb_sysopen – Cars <Errno::ENOENT>
from ex13_alt_2.rb:10:in ‘gets’
from ex13_alt_2rb:10:in ‘<main>’

ex 13 alt 5

After some reading I learnt that when ARGV is present in a script, by defaut gets will read from ARGV if there is anything inside it which is what caused the error. There are two ways arond this; first we can clear out ARGV by calling .clear on ARGV like this:

ex13 alt 6.png

Or we use the standard input, or $stdinwhich says ‘get this input from the users keyboard thus:

ex13 7

Either of these should return this:

ex13 8.png

Learn Ruby the Hard Way, Excercise 12: Prompting People for Numbers

After looking around the web I’ve found a few other people have been reading Zed Shaws’s Learn Ruby the Hard Way and making blog posts about their progress, including this most totaly excellent blog  Stacey Learns to code I figured I would do the same thing/

I was going to post excercises form the start of the book, but decided I couldn’t be bothered so here is excercise 12.

Excercise 12: Prompting People for Numbers

 

ex12 1.png
The code for excercise 12
ex12 2.png

excercise 12 consol

Study Drills

1. Try out the .to_f operation. What does it do?

.to_f stands for To float it converts data to a float, which is a decimal number. I used this in the next study drill

2. To play with .to_f more, make a small script that asks for some money and gives back 10% of it. If I give your script 103.4 dollars,  your script gives back 10.34 in change.

Ok sure here you go:

ex12 4
Excercise 12 study drill 2
ex12 3
Excercise 12 consol

 

 

 

 

 

 

 

 

Zed Shaw’s Learn Ruby the hard way

I’ve recently started reading Zed Shaw’s beginner book for Ruby “Learn Ruby the Hard Way.” As the front page suggests it’s a fairly simple and straightforward approach to learning Ruby and despite what the title it’s not that hard to get into and quite interesting. The book assumes you know nothing about programming and has a structured approach, learning through exercises, your own research in study drills and using repetition to gradually introduce new concepts as you go forwards. Also…..the author doesn’t do the thing I HATE the most in beginner books which is to to teach incantations, by which I mean introducing a concept fo a few pages then jumping ahead, never to revisit the subject again and assuming it all married in your mind without any exposition (looking at you Codecademy.)

 

 

20170628_223026

 

 

Corrupting bitmap files

I’ve been playing around with Victor X’s most excellent Bitmaps & Waves software

(http://victorx.eu/BitmapPlayer.htm)

Bitmaps and waves converts images to sound and visa versa and I often use this to make stuff for the freesound Project

(https://freesound.org/people/CuddleNucks/)

But today I thought I’d try playing aorund with the leftover converted images once they have been “used up” in the process like below which is the leftover of a screenshot from Fallout 3 that was converted back and forth from Wave file to Bitmap.

5.jpg

These can be post processed to make something really cool, there are a lot of free and easy tools on the web for things like this – the reults are often pretty unpredictable but I think thats were the fun comes into it, also the frustration!