Advertisement
  1. Code
  2. Ruby

Ruby for Newbies: Variables, Datatypes, and Files

Scroll to top
Read Time: 4 min
This post is part of a series called Ruby for Newbies.
Ruby for Newbies: Installing Ruby and Getting Started
Ruby for Newbies: Working with Classes

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:

1
2
my_string = "Hello, World!"
3
4
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:

1
2
greeting_1 = 'How\'re y\'all doin\'?'
3
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 }:

1
2
name = "Andrew"
3
greeting = "Hello, my name is #{name}"
4
5
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:

1
2
ten = 10
3
fifteen_point_two = 15.2
4
5
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:

1
2
billion = 1_000_000_000

Arrays

There are two ways to create an empty array:

1
2
my_arr = Array.new
3
4
my_other_arr = []
5
6
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.

1
2
my_arr.push("foobar")
3
my_arr[1] = "gizmo"
4
5
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:

1
2
my_hash = Hash.new
3
4
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.

1
2
my_hash["name"] = "Andrew"
3
4
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:

1
2
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:

1
2
name = "Andrew"
3
4
name.upcase # "ANDREW"

5
6
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.

1
2
name = "Andrew"
3
name_2 = "Joe"
4
def name.add_last_name
5
  "#{self} Burgess"
6
end
7
8
name.add_last_name # "Andrew Burgess"

9
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.

1
2
name = "Joe"
3
name_2 = "Andrew"
4
5
class String
6
  def add_last_name
7
    "#{self} last_name_goes_here"
8
  end
9
end
10
11
name.add_last_name # "Joe last_name_goes_here"

12
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:

1
2
name = "Joe"
3
4
def name.shout
5
  "#{self.upcase}!!!!"
6
end
7
8
puts name.shout

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

1
2
$ ruby your_file_name.rb
3
JOE!!!!

Conclusion

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

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.