Wednesday, February 2, 2011

Working with Arrays in Ruby

Since I've been off work for two days thanks to ICEPOCALYPSE 2011, I've had some extra time to work with Ruby. I haven't been as diligent as I'd like. But I've spent a good couple hours each day working through Beginning Ruby and reading about Ruby online, so it's not a total wash.

Today I've been learning about arrays. Arrays are collections of elements and once elements have been put into an array, you can tell Ruby to manipulate them in various ways.

Here's some example code from Beginning Ruby:

x = [3, 7, 8, 9]
puts x.first
puts x.last

This makes sense. We have an array known as x, with four elements (3, 7, 8, and 9)
The rest of the code will display the first element and then the last element (3 and 9)

Once I saw how that worked, I wondered if some of the other ways of manipulating data I've learned previously would work. So I expanded on the example code:

x = [3, 7, 8, 9]
puts x.first
puts x.last
z = x.last - x.first
puts z
y = x.last / x.first
puts y
a = x.last ** x.first
puts a
puts "Yes, 9 is larger than 3" if x.last > x.first

So now in addition to listing the first and last element, the code also subtracts the 3 from 9, divides 9 by 3, multiples 9 by the third power, and then displays that 9 is, in fact, larger than 3.

Ruby is easy to work with, once you've got an idea of how it works. Learning Ruby won't be a matter of memorizing every possible bit of code, but a matter of learning how to tell it to perform a series of tasks.

My goal for the evening is to get through the end of chapter 3 (Hashes await!) so I can get started on chapter 4, which will take me through building an actual program.

2 comments:

  1. Hey Tyler,

    I'm learning Ruby (well, Rails to be more specific) too and starting from absolutely 0 programming experience.

    My process thus far has been to work through www.railstutorial.org and now I'm halfway through "Learn to Program" by Chris Pine. I wish I'd done those in reverse but they've been great resources, especially considering my total lack of prior experience.

    Will you be at the Ruby meetup next week? We should chat. My email is rbrennanknotts gmail.

    ReplyDelete
  2. Hey Brennan,

    I took a look at railstutorials.org and I'll probably get started on that once I'm done with the first 4 or 5 chapters of Beginning Ruby. So far I've used both Hackety Hack (http://hackety-hack.com/) and Ruby in 20 Minutes (http://www.ruby-lang.org/en/documentation/quickstart/) as supplemental material.

    I will definitely be at the meetup next week. Your comment actually reminded me of it and I was all "Oh yeah, I should go to a meet up."

    My email is tylerlmoore@gmail.com, I'd love to chat with another newbie.

    ReplyDelete