Ruby for Newbies: Variables, Datatypes, and Files
basixvideos

Ruby for Newbies: Variables, Datatypes, and Files

Tutorial Details
  • Topic: Ruby
  • Difficulty: Easy
  • Estimated Completion Time: 30 Minutes
Download Source Files
This entry is part 2 of 13 in the Ruby for Newbies Session
« PreviousNext »

Ruby is a one of the most popular languages used on the web. We’ve recently started a new screencast series here on Nettuts+ that will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. Today, we’ll look at the basic Ruby datatypes, as well as using variables and storing your Ruby code in files.


Catch Up


View Screencast


Ruby’s Basic Datatypes and Objects

In this chapter, we’ll introduce you to the basics of Ruby datatypes.

Strings

Ruby strings aren’t much different from other languages you’re probably used to. You can use both double quotes and single quotes to create strings:

my_string = "Hello, World!"

my_other_string = 'What's going on?'

Of course, if you want to use the same type of quote within the string, you’ll have to escape it:

greeting_1 = 'How\'re y\'all doin\'?'
greeting_2 = "\"How are you doing?\" she asked."

Ruby offers string interpolation: “embedding” the result of some code inside a string. You’ll probably do this most often with variables, but you can execute any code you’d like in there. The code you are interpolating goes between #{ and }:

name = "Andrew"
greeting = "Hello, my name is #{name}"

addition = "25 x 8 = #{25 * 8}"

Numbers

Ruby can handle both integers and floating point numbers (numbers with decimals), and it does it just how you would expect:

ten = 10
fifteen_point_two = 15.2

twenty_five_point_two = ten + fifteen_point_two;

Here’s the first of many pieces of syntactic sugar we’ll see: you can use an underscore as a thousands divider when writing long numbers; Ruby ignores the underscore. This makes it easy to read large numbers:

billion = 1_000_000_000

Arrays

There are two ways to create an empty array:

my_arr = Array.new

my_other_arr = []

my_third_array = ["one", "two", "three"]

It’s easy to create an array with elements in it, as you can see.

To add an item to an array, you can use the push method, or use square-bracket notation, putting the appropriate index in the brackets. You can use square brackets to get the values back, as well.

my_arr.push("foobar")
my_arr[1] = "gizmo"

my_arr[0] # foobar

Hashes

A hash in Ruby is like an object literal in JavaScript or an associative array in PHP. They’re made similarly to arrays:

my_hash = Hash.new

my_other_hash = {}

To put item in a hash, you again use the square-bracket notation. You can use any value as the key, but strings, or symbols (coming up next) are common options.

my_hash["name"] = "Andrew"

my_hash[:age] = 20

To create a hash with objects in it right from the beginning, you use a notation almost identical to JavaScript’s object literals; the only difference is that Ruby uses an arrow (=>) between keys and values:

person = { :name => "Joe", :age => 35, :job => "plumber" }

Symbols

Symbols are light-weight strings. They’re often used as identifiers, in places other languages would often use strings. They’re used instead of strings because they can take up much less memory (it gets complicated, so I’m trying to keep it simple; if you want to read more check out this article).

To create a symbol, simply precede a word with a colon; you can see a few examples of this in the code snippets above.

True, False, and Nil

These values work just as you’d expect them to. Nil is Ruby’s “nothing” value, although it is an object.


Methods on Objects

Because everything in Ruby is an object, pretty much everything has methods that you can run:

name = "Andrew"

name.upcase # "ANDREW"

name.downcase # "andrew"

You can easily add methods to objects. The first way is by adding a singleton method. This is a method that is put only of a single instance of an object.

name = "Andrew"
name_2 = "Joe"
def name.add_last_name
  "#{self} Burgess"
end

name.add_last_name # "Andrew Burgess"
name_2.add_last_name # NoMethodError

If you wanted all strings to have this method, you could so this by opening the String class and adding an instance method.

name = "Joe"
name_2 = "Andrew"

class String
  def add_last_name
    "#{self} last_name_goes_here"
  end
end

name.add_last_name # "Joe last_name_goes_here"
name.add_last_name # "Andrew last_name_goes_here"

Ruby Files

Of course, you’ll want to put your Ruby code in files as it gets longer. Just give that file an extension of .rb, and you should be good.

Try putting this in a file:

name = "Joe"

def name.shout
  "#{self.upcase}!!!!"
end

puts name.shout

To run this code, open your terminal and run this:

$ ruby your_file_name.rb
JOE!!!!

Conclusion

That’s it! Let me know if you have any questions in the comments!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.ferus.info maciej

    There is an error on the main page – need –more– tag.

  • Eduardo Barros

    Great tutorial, very useful.
    Hoping for some more of these ruby tutorials soon..

  • Arun Kurian

    Hey, I don’t know if you guys forgot to include the ‘more’ tag but the index page of nettuts is completely messed up.

    • http://www.dazydude.net Rik de Vos

      Just what I was going to say :)

  • http://laroouse.com esranull

    nice post thanks a lot

  • dj

    Andrew – informative cast. You may want to watch the recording level more closely – this had to be cranked way up to be able to hear at all. And you know, talking and typing at the same time isn’t easy so you could slow it down a bit in order to prevent so many errors and backspacing – a real time waster. Just thought you’d like to know. Enjoy the series, keep it up.

  • http://dogmatic69.com dogmatic69

    pretty painful watching that… never seen backspace used so much in one video

  • Andrew

    My name is Andrew and I’m 20 as well!

  • http://www.daft-thoughts.com Ross

    Its just so…… clean. *ogles the Ruby examples*

  • http://as 7th

    8th!

  • http://twitter.com/mixn Milos Sutanovac

    Great series, Andrew.

    There’s just one thing that confused me at around 20:50 …

    How come you don’t have to do something like:

    var = String.new

    first before you can access the add_last_name_2 method? Are Rubys’ methods inside classes static by default?

    I’m very new to programming, especially Ruby, so sorry if I missed something. :)

    Keep up the good work!

  • http://andrewburgess.ca Andrew Burgess
    Author

    @everyone – thanks for the comments, glad you’re enjoying the series. I’ll see what I can do about turning the volume up next time. And I’ll try to avoid the backspace key, too :)

    @Milos – First off, you could create strings using the String.new syntax. However, when you open up a class, like we did here . . .

    class String  
      def add_last_name  
        "#{self} last_name_goes_here"  
      end  
    end
    

    . . . you’re just adding a method to the String class. This is an instance method, so all instances of String—including those already created—get access to this method. Does that help?

  • http://www.demogeek.com DemoGeek

    Ruby is certainly very elegant of the many languages out there, no doubt about it. I just need to get a handle on Rails and the deployment options for Rails and then I can call myself a RoR guy! :)

  • http://www.twentyeleven.co.uk TwentyEleven

    Sorry, but since when did you have adverts on Nettuts videos.

  • http://www.jc-designs.net/blog Jeremy Carlson

    Good screen cast Andrew. This series says for newbies, which I am, but I also don’t know PHP. Are you going for people with no programming background or for people trying to learn a second language in this series? Because there is definitely a difference. I have some basic knowledge of what certain things are, like arrays, but I had to look up what the hell a ‘hash’ was in a book I just bought. Is PHP a pre-req for this tut series? If not, can you please define things a little more…cleanly. You are starting from the very beginning of Ruby so an idiot like me can start learning, but then throw in some stuff with the assumption that I will know what the f you are talking about. I’m not sure how many people are finding it helpful when you mention things like “In PHP you would do this…”, but for me that does nothing.

    I am picking Ruby as my first language because I am a front ender that is using Sass. I just don’t have any other programming knowledge (obviously jQuery doesn’t count in that regard).

    Anyway, I am not bitching, just commenting because I did learn a LOT in this screen cast, and I really REALLY want to see more. I am very excited to see the next one, keep it up!

  • http://www.webdesignerhouston.com Houston Web Designer

    Hey nice tutorial. Really helpful for ruby beginners. They will get an overview and idea about it.
    Thanks for the information.!!!

  • http://www.jmonit.com Monit

    Thanks a lot. Ruby looks great.

    Keep up the good work.

  • Tipugin

    Gr8! Ruby > PHP

  • http://brettic.us Bretticus

    Nice tutorials Andrew. I am enjoying them very much.

    I have been writing PHP for several years. I think most people think ruby-on-rails when they think ruby, so providing common ground in your tutorials for PHP is absolutely appropriate. Hopefully persons will see that ruby is also a great language for writing standalone scripts. In the past, I have written many standalone scripts in python. It’s nice to get a video tutorial on ruby and see great options (such as how easy it is to extend core objects!)

    I hope you’ll follow up with a rails series (I know there are millions out there but nobody does them like nettuts!)

    Thanks again!

  • Oscar B.

    Hey Andrew, you are doing a great job, thanks a lot!!!!!!
    Im a RoR lover, but I haven’t time to continue my learning process.

    Thanks!!!!!!!!!

  • thomasfedb

    Your first string example is broken.

  • http://360signals.com Jow

    Thank you so much Andrew!

    I noticed a really important thing that you did, which is referencing and comparing to PHP and other languages, which is incredibly helping me (and others) figure out ruby the best way.

    I’m really enjoying following up this series and I can’t wait to learn more from your tuts. Really great job.

    :)

  • marcos cerutti

    Hey pal, amazing tutorial. you’re really good to explain things!!!!

  • Craig

    Can you please increase the volume on the video file, even with my volume turned up all the way on both the player and my laptop it’s hard to hear.

  • Kris

    Hi Andrew, I like how you set up your command prompt. Can you share your PS1 variable? Thanks

  • kris

    the variable would be something like this if anyone else was wondering lol

    PS1=”kris:: \n–› “

  • Scott

    Great introduction! I hope can cover some more ruby soon!

  • http://www.wplancer.com Banago

    I’m just into Ruby and I find it cool, very easy to type. Having a PHP background however, I find it a little confusing declaring variables like this @var and :var (in arrays) – I would remember it better if it was the same.

  • http://www.twitter.com/evilmeteor Jaime

    There’s an error in the text

    name.add_last_name # “Andrew last_name_goes_here”

    Should be

    name_2.add_last_name # “Andrew last_name_goes_here”

  • http://www.anti-radary.info Ginny

    class String
    def add_last_name
    “#{self} last_name_goes_here”
    end
    end

    Why? You don’t need class String. Without specifing variable in def (I mean: def name.add_last_name), this method can be available for all variables.

  • ben

    Nice tutorial, very easy to understand and get you grounded

  • http://andredublin.com Andre Dublin

    Thanks so much for this, RVM made life a lot easier for me also. However I had to do a little hunting for information about installing RVM which can be found here

    http://railscasts.com/episodes/200-rails-3-beta-and-rvm

    creating a .bash_profile or .bashrc

    http://www.redfinsolutions.com/redfin-blog/creating-bashprofile-your-mac

    Hope this helps anybody else going through this tut.

    Thanks again Andrew!

  • http://ibizsol.tk Kashif

    i am developing in php from last three years, yesterday i came across this tutorial series, and after reading just first two tutorials i am enjoying programming in ruby language, its really very interesting.

  • http://www.bid.kadeparchment.com kerron

    would love a PDF version of the commands you went through in the tutorial. Maybe you could save it in a pdf file along with posting the scripts online?
    cheers

  • http://www.everythinginkonline.com Mike

    Okay…so everyone seems to be so pleased with this screencast – I really am not, this was supposed to be an introduction for newbies…just like most of the other “newbie” tutorials on this site I find the exact same issue here. Terminology being used that relate to other programming methods. In other words if I already have Java, PHP, Javascript programming experience then this is for a newbie…or at least a newbie to Ruby. But this definately is not for a newbie to programming. strings…functions…classess….this is all great but what the hell are they all for?!?!?!? Where are they used, why would I add a string, where would I use a function, what name should the function be?!??!?!

    It would be great if some of the tutorials on here actually explained things so that a true newbie could understand. I’m going to go through all of this again and see if it sinks in but it would be great to see some real world explanation included with these examples…this is just a thought coming from someone that spent 5 years as a corporate trainer and instructional designer.

    Overall – not impressed and once again not seeing the value in the instruction for the premium fees!!!

    Disappointing.

    • Johnny Farina

      This is a screencast for newbies to RUBY, not newbies to programming.
      If you wanna learn the basics of programing I reccomend you go to http://amazon.com and buy yourself an introductory book so you can understand the VERY basic things like ” strings…functions…classess….”.
      Ruby is an OOP language, so you SHOULD have a bit of knowledge on programming to even think about learning the basics of it.

      P.S. There’s a very good book for people like you in amazon, Beginning Programming For Dummies, it’s on its 4th edition so it should be really well structured.

      Come back when you can understand ” strings…functions…classess….” lol.

      Hope this helps you.

  • http://www.assemble.co.za Billy

    Thanks for this tutorial. Only discovered it now, wish I had gone through it when I started learning Ruby as some fundamentals were covered here that could have saved me some time.

    Some people here are raising the issue of you comparing Ruby to PHP. I don’t see this as a problem, simply because those references have helped many here who are new to Ruby who have a PHP background. For those who’s first language is Ruby, don’t get intimidated by this, just be relieved that you’re starting with something that to me is much more elegant than PHP in many ways.

    What I would suggest, Andrew, for the absolute newbies, is to include a glossary of the terms you use that we assume everyone knows. Perhaps it can be separate from the video so it won’t waste time or feel unbearable for those coming from other languages. Perhaps even linking to other sites that give some beginner fundamentals to OO programming.

    It would be nice to link away because it probably falls outside of the scope of explaining Ruby.

  • http://catinacrate.com Joseph Curcuru

    Thanks, very helpful.

  • http://www.devasto.org video youtube

    Great tutorial!

  • Troels

    Under the heading “Methods on objects” it says “This is a method that is put only of a single instance of an object.”

    What does this mean, could it be said in a clearer fashion?

  • Jay Vee

    Horrible. Absolutely and completely horrible. You may know how to use Ruby but you suck as a teacher. You make far too many mistakes and the screen image is way too small. Redo all of these with a different teacher and with the text editor zoomed in and they will be good. At the very least write a script and practice it! Do not just make things up as you go along. Again, these tutorials suck.

    • http://www.jeffrey-way.com Jeffrey Way

      Are you viewing in HD?

    • metrobee

      to: jay wee. You ‘re joking right? otherwise i could not disagree more with you

    • Johnny Farina

      Go get yourself enrolled in a school. They give you better streen than your’s and a mouse that works when you wanna click the FULLSCREEN button.

  • yura

    Great tutorials, i did perl, python, now ruby -and i can tell it’s ruby all the way -comfy and perly a bit– the only problem i had with hashes-i did use 2 different machines – so why is that?

    my_hash["name"] = “Andrew”
    ined local variable or method `my_hash’ for main:Object
    b):1
    Ruby192/bin/irb:12:in `’

    one more -nice topics for workin’ with files, i would like to see more stuff for reg exes -like pattern matching in several files in the same directory

  • yura

    Please sorting various array by field number

  • David

    Great tutorial. Thanks for posting it. I never realized how nice and intuitive ruby is until I started following along with your tutorial just now.

  • Jambi

    Shhhhhhsh! Tawk vewwy vewwy kwi-et-wee. Wuh twaining in woo-bee. Seriously, I can scarcely hear you Andrew.