Advertisement
Ruby

Ruby for Newbies: Variables, Datatypes, and Files

by

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!

Related Posts
  • Code
    Web Development
    Testing Your Ruby Code With Guard, RSpec & Pry: Part 2Ruby wideretina preview
    Continue learning test-driven development in Ruby with Guard, RSpec and Pry.Read More…
  • Code
    JavaScript & AJAX
    JavaScript ObjectsCover
    In JavaScript, objects are king: Almost everything is an object or acts like an object. Understand objects and you will understand JavaScript. So let's examine the creation of objects in JavaScript.Read More…
  • Code
    Ruby
    Using New Relic Custom Metrics to Monitor All the ThingsGetting started new relic retina preview2
    When you first get introduced to New Relic, it's easy to be overwhelmed by all the features. But like with most tools, as you slowly climb the learning curve and get familiar with the features provided out of the box, you begin to wonder how it all hangs together under the hood and if there is more you can do with what you have at hand.Read More…
  • Code
    iOS SDK
    Objective-C Succinctly: Data Types0e5ds8 preview image@2x
    Objective-C has two categories of data types. First, remember that Objective-C is a superset of C, so you have access to all of the native C data types like char, int, float, etc. Objective-C also defines a few of its own low-level types, including a Boolean type. Let's call all of these "primitive data types."Read More…
  • Code
    Ruby
    Exploring RackExploring rack retina preview
    If you're a Ruby programmer who has done any kind of web development, you've almost certainly used Rack, whether you know it or not, as it's the foundation which most Ruby web frameworks (Rails, Sinatra, etc.) are built upon. Let's dig into some of the basic concepts of Rack and even build a small app or two.Read More…
  • Code
    Ruby
    Active Record: The Rails Database BridgeRelational databases for dummies preview
    In the past, to build a web application, you required the skills to code in your business logic language and your database language. More recently, however, back-end frameworks are leaning toward using Object-Relational Mapping (ORM); this is a technique that lets you manage your database in the business logic language that you're most comfortable with. Rails uses an ORM in the form of Active Record. In this tutorial, we'll dive into Active Record and see what it can do for us!Read More…