Posted 11.01.12

Ruby, Using External Files

Day 3 of Ruby! So far, we’ve…

Today, we’ll learn how to read and write to external files. But, first, I wanted to look back at the last piece of code we wrote yesterday, a simple Mad Lib application.

puts "We're gonna fill out a Mad Lib."
puts "Adjective?"
adjective = gets
puts "Place?"
place = gets
puts "Plural Noun?"
plural_noun = gets
print "Today was a ", adjective, " day. I went to ", place, ". It was filled with ", plural_noun, "."

I provided 2 other ways this could be written. But, there’s another way, that I think is far better than all of these options:

puts "We're gonna fill out a Mad Lib."
puts "Adjective?"
adjective = gets
puts "Place?"
place = gets
puts "Plural Noun?"
plural_noun = gets
puts "Today was a #{adjective} day. I went to #{place}. It was filled with #{plural_noun}."

Yes, in every case the output is the same. However, in my humble opinion, this last version is far more readable.

So, what’s happening on the back end? Well, when you use #{…}, it doesn’t appear on screen, instead, ruby evaluates what’s between #{…} and displays it’s value instead.


Now, for bigger and better things. Reading and writing out to external files. We’ll still use our Mad Lib example.

Let’s create 3 different files, one for each: adjective, place, and plural noun.

Terminal - adjective.dat

Inside adjective.dat, I simply entered juicy, saved and closed.

Terminal - place.dat

Inside place.dat, I simply entered Nashville, saved and closed.

Terminal - plural_noun.dat

Inside plural_noun.dat, I simply entered cowboy hats, saved and closed.

In our Mad Lib code, I’ll update it to read:

puts "We're gonna fill out a Mad Lib."
puts "It's OK, I can grab all the information I need from existing files."
adjective = File.read("adjective.dat")
place = File.read("place.dat")
plural_noun = File.read("plural_noun.dat")
puts "Today was a #{adjective} day. I went to #{place}. It was filled with #{plural_noun}."

Instead of telling the Terminal to get the code from the keyboard, I tell it to read the File object and I pass in the file name. Pretty straightforward. Don’t you think?

Well, what about saving it out? I’ll need to create a new File object and make sure I can write to it.

Let’s update our code to this:

puts "We're gonna fill out a Mad Lib."
puts "It's OK, I can grab all the information I need from existing files."
adjective = File.read("adjective.dat")
place = File.read("place.dat")
plural_noun = File.read("plural_noun.dat")
mad_lib_file = File.new("mad_lib.out", "w")
mad_lib_file.puts "Today was a #{adjective} day. I went to #{place}. It was filled with #{plural_noun}."
mad_lib_file.close

That added a few more lines of code, but don’t worry, I’ll explain it.

mad_lib_file = File.new("mad_lib.out", "w")

I created a new file object, called mad_lib_file. When I created the file, I gave it a filename, mad_lib.out, and told it that I needed it to have a mode of w (for write).

mad_lib_file.puts "Today was a #{adjective} day. I went to #{place}. It was filled with #{plural_noun}."

Instead of printing to the screen, I wanted to print to our new file object. So, I passed the object (left side of the .) a message (right side of the .) puts "Today was a...

mad_lib_file.close

I closed the file. Done.

Now, when I run the file in the Terminal:

Terminal - Write to an external file

and if I open mad_lib.out

Sublime - mad_lib.out

Still with me? If you have questions, comment below. Tomorrow, we’ll put on our big boy Ruby pants and start looking at objects.


Be the First to Comment :: Leave a Comment :: Permalink

TAGS




Posted 10.31.12

Another Day, Another Look at Ruby

Another day, another look at Ruby.

Yesterday, we got set up and printed something to the screen.

Today, we’ll look at variables and getting keyboard input from the user.

If you don’t have a lot of programming experience, a variable is simply a container for storing information. It’s a factor we don’t know. This isn’t any different from the way we talk. Somebody might say, “They said x.” x is simply a container for information.

When we’re naming our variables, there are a few rules and naming conventions.

Today, we’ll just be looking at local variables and they always

  • Start with a lowercase letter or an underscore
  • Contain letters, underscores, and/or digits
  • Use underscores instead of camelcasing

***

In our first program, let’s do something as simple as add 2 to a given number. I know, this is something you could easily do in your head, but I want to illustrate a bigger programming concept.

Navigate to the Ruby folder we created yesterday and create a new file plus2.rb

Terminal - Create plus2.rb

Inside your file, type:

x = 5
puts x + 2

Now run your program. If all goes as planned, you should see:

Terminal - plus2 = 7

Sweet, we’ve used variables. Now, let’s make it a little more complicated. Let’s let the user input what x should be. To do that, we’ll use gets Update your code to read:

puts "Give me any number and I'll add 2"
x = gets
puts x + 2

Run your program. Give it any number and hit enter. You should get something like this:

Terminal - to_i

What happened?! Well, when you entered something from the keywobard, Ruby thought it was a string (a string of letters), not an integer. There’s a difference between “100″ and 100. The computer might as well see “100″ as “one hundred” because of the “”. We know they’re the same, but it doesn’t. So, we need to tell it that when the user enters a number it’s an integer.

puts "Give me any number and I'll add 2"
x = gets
puts x.to_i + 2

Run it.

Terminal - Keyboard Input

Perfect!

Now, let’s make this is a little more fun. Let’s create a Mad Lib. Remember those?

Let’s talk about the logic first, that always helps.

Today was a adjective day. I went to place. It was filled with plural noun.

Create a new file and call it mad_lib.rb

Here’s the code:

puts "We're gonna fill out a Mad Lib."
puts "Adjective?"
adjective = gets
puts "Place?"
place = gets
puts "Plural Noun?"
plural_noun = gets
print "Today was a ", adjective, " day. I went to ", place, ". It was filled with ", plural_noun, "."

Notice how we strung our final sentence together. We could have done this several different ways, all would have achieved the same result.

print "Today was a " + adjective + " day. I went to " + place + ". It was filled with " + plural_noun
print "Today was a "
print adjective
print " day. I went to "
print place
print ". It was filled with "
puts plural_noun

Regardless, this is the result:

Terminal - Mad Lib


Be the First to Comment :: Leave a Comment :: Permalink

TAGS




Posted 10.30.12

I Decided to Look at Ruby on Rails

I’m a PHP girl. I’ve been writing PHP for the past 7 years. I’ve heard so much about Ruby lately that it’s hard not to wonder, “Is it really all it’s hyped up to be?” I’ve been reading plenty of blog posts (here and here) trying to decide if it’s worth investing the time to learn (yet) another programming language. Part of me is eager is to learn something new and is up for a new challenge. I like to think, the more tools I have in my toolbox, the better suited I’ll be for various projects. … So, this is my journey to learning to looking at Ruby and Ruby on Rails. Join me, if you want, we can struggle together.

…yes, the two (Ruby and Ruby on Rails) are different. Ruby is the programming language. Ruby on Rails is the framework that sits on top of Ruby. If I can put it in PHP terms, PHP is the language, CodeIgniter is the framework. Great, so, what’s a framework?

Well, for almost every project, there certain things you always have to do. Websites, for example, I (almost) always have to connect to the database. I could write that code every time, or I could use a framework that has built in functions that do the work for me. A framework gives me structure and a starting place.

While I’m eager to get my hands dirty and jump in with Ruby on Rails, I know I first need to learn Ruby before jumping in the deep end. Rails will make a whole lot more sense and I’ll be able to go a whole lot further in the long run, if I have a foundation first.

I’ve seen The Well Grounded Rubyist mentioned several times on various sites, so I decided to buy the book and start reading. Call me old school, but I prefer books over videos. I like being able to set my own pace, actually see the words, highlight and take notes. I’ve also looked at Code School, but for where I’m at right now, I feel like it moves a little fast and I’m having trouble connecting all the pieces together. I might find it more helpful, though, after I have a few chapters with this book under my belt.


Installing Ruby

I work off a MacBook Pro, running Snow Leopard (I know). It came with Ruby already installed, but it wasn’t the latest version.

I found an excellent blog post by David Benjamin explaining how to get everything up to speed.

I don’t want to be redundant, so I’ll let you click over (just this once) and read his post. –However, I will share a few of my hold ups:

I don’t have a lot of experience with the terminal.

I took a C++ class in college where we had to use the Terminal, so I at least have a basic understanding, but it’s been a while and really, the only commands I still remember are:

cd change directory
pwd display the current path
ln display the contents of the current directory

NetTuts has several posts that will help you get comfortable with the Terminal:

I use Sublime instead of TextMate.

So, instead of using the mate command (as listed in the instructions) to create a new file, I figured out how to call Sublime from the command line:

ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" ~/bin/subl

So instead of saying mate ~/.profile, I used subl ~/.profile

I had trouble finding the bin folder.

I finally found it. If you go to the root directory > usr directory, it’s there.

Terminal - Finding the bin Folder

With those things out of the way, I was able to easily follow Dan’s instructions.


Understanding the difference between Ruby and ruby

(Apparently) the difference between Ruby and ruby is more than just an upper and lowercase letter. Ruby is the actual language, while ruby is the interpreter.

So, you’ll write Ruby files (with the extension .rb). Then, when you get ready to run the file, you’ll use ruby in the command line to interpret the file for you.


Your first Ruby Program

Create a folder called Ruby for all our code. Mine’s sitting in my Documents folder. Don’t worry, I didn’t do anything fancy like use the Terminal. I simply created it in finder. I’ll keep all my Ruby code there (crazy, I know).

In Sublime, I’ll create a new file and save it to that folder. I’ll call it “first_program.rb”

…BUT… if you did want to be fancy and feel really smart, you could do all this from the Terminal:

Terminal - mkdir for first Ruby program

Inside the file, I’ll type:

puts "I'm writing Ruby"

Save!

Now, in the Terminal, I’ll navigate to that folder. I’ll run the interpreter:

Terminal - ruby first_program.rb

Magic!

…If you don’t see this and got something like this, go back to your file in Sublime and make sure that you have code quotes " " and ' and not fancy ones.
Terminal - error when running ruby first_program.rb

OK, so what just happened in our code?! (It drives me crazy when authors say “Write this.” I write it and they say “Good job!” and I don’t even know what I wrote or what I did! For me, it’s just as much (if not more) about understanding the code, so I can use it in various circumstances in the future, as it is about completing the exercises.

In Ruby puts just means print. Send it to the screen. If you’re a PHP person (like I am), it’s just like echo. The only difference, is that puts adds a line break automatically to the end. So, none of this “\n” junk.

NOTE: Where did they get puts anyway? That doesn’t even sound like good English! Well, it’s an abbreviation for put string.

What if you want some of that “\n” that junk? Well, Ruby has another method you can use called print that doesn’t add “\n” to the end. I’ll show you what I mean. Open your first_program.rb back up. Update it to look like this:

puts "I’m writing Ruby"
print "This is my first program and "
print "it runs like a champ."

Save. Now, back in the Terminal, run your ruby first_program.rb command again.

NOTE: In the Terminal, you can hit the up arrow on your keyboard and it will automatically pull up the last command you entered. Keep hitting the up arrow and it will keep cycling back, showing the command before that. This makes it helpful, especially if you keep running the same commands over and over again.

See what I mean with the difference between puts and print?

Terminal - puts and print


OK, so, this might seem super simplistic, but the important part is we’ve started(!) and that’s something worth celebrating!

Below, I’ve listed a few tutorials that I’ve dabbled in, if you want to jump in a little deeper or move a little faster!

Tutorials


Be the First to Comment :: Leave a Comment :: Permalink



Powered by Wordpress