Intro to Ruby - Data Types & Variables

Objectives

  • Identify and describe use cases for Ruby's data types
  • Describe the different types of variables (locals, instance, constants) in Ruby & when to use them

Intro

Now that we've got your feet wet with HTML, CSS, and JavaScript, you've got a taste of what it's like to start building for the web – and we're about to kick it up a notch.

Originally, the web was meant just as a place for documents – HTML pages that linked to each other, that was it.

But as developers started creating more and more pages, and desiring more and more interactivity with those pages, we got to a point historically where we started writing that created HTML for us. That was where the concept of web development frameworks came from, and undoubtedly one of the most prolific has been Ruby on Rails – one of the first frameworks to use the language of Ruby to build web applications.

We're not going to jump right into Rails immediately, we're going to build up to it over the course of the next week, and make sure you have an understanding of the concepts that go into building it first.

But even before that, let's get our hands dirty with some straight Ruby. It's super readable and easy to get started with, you're gonna like it a lot.

Humble Origins

Ruby is an object-oriented language suitable for writing day to day scripts as well as full-scale applications. Yukihiro Matsumoto, or "Matz", began work on Ruby back in 1993, because he wanted a language that made him productive while being fun to use. Initially popular in Japan, Ruby has been finding its way into the hearts of programmers all over the world.

  • Ruby stylistically conforms to the snake_case convention
  • The documentation is fantastic

Further reading: The Philosophy of Ruby

Follow along!

As we experiment with Ruby syntax, you should follow along and try things yourself. Do what we do, but feel free to mess around and try your own little experiments too.

We're gonna use IRB, our Interactive Ruby Shell, so we can type some Ruby commands and see exactly what happens in real time, and you can follow along and code.

Open up your terminal, and from anywhere, type irb IRB in Terminal

The Beauty of Ruby

There are a few general points to know about Ruby, and then we're going to be comparing the details of writing Ruby to what you already know in JavaScript.

We'll go over a bunch of basics you need to know in the next two days.

One of the things that's important to people who write code in Ruby is how the code reads. Rubyists are known for wanting beautiful code, and writing it in a way that reads as much like normal English as possible. That's part of what makes it great for beginners, is that it's instantly readable.

Check out this example:

def make_a_sentence(words)
  words.join(' ') + "!"
end

make_a_sentence(['You', 'are', 'already', 'experts'])
# => "You are already experts!"

Without knowing anything about Ruby you can probably sort of understand how all this works. Nice, right?

Data Types

Question: What data types have you guys been using in JavaScript? Let's write them on the board.

  • Booleans are written as true and false
  • Numbers are written as 12 or 9.45
  • Strings are written as "awesome"
  • Arrays are written as ['x','y','z']
  • Objects are written as {key: 'value', thing: true, stuff: [1,2,3]}

Now, let's see which of those are similar in Ruby, and which are different.

  • true or false are still booleans (technically TrueClass / FalseClass)
  • nil, the equivalent of nothing (technically NilClass)
  • there's no Undefined object. If something is undefined it'll just say so.
  • 16.2 is a Float and1 is an Integer (technically a FixNum, but you can consider it the same thing)
  • "hello world" is still a String
  • [1,2,3,4] is still an Array
  • {keys: ['some', 'values'] } is called a Hash, but works the same

Most importantly, in Ruby, everything is an object. We'll talk about that in more detail later, but that means that each of the above data types have methods & properties just like our JS objects did.

To recap:

  • Booleans are written as true and false
  • Integers are written as 12
  • Floats are written as 9.45
  • Strings are written as "awesome"
  • Arrays are written as ['x','y','z']
  • Hashes are written as {key: 'value', thing: true, stuff: [1,2,3]}

Comments.

Comments in JS look like this:

// I'm a comment

Ruby's are like this:

# No, I'm a comment

Converting between data-types

If we want to convert one data type to another in Ruby, there are some built-in methods that we can use. We'll take a look at built-in methods in more detail in a later lesson, however for the minute let's use them and see the result:

# Converting an Integer to a String
1.to_s
#=> "1"

# Converting a String to an Integer
"10".to_i
#=> 10

These type-conversion methods usually start with .to_.

Duck-typing

Unlike JavaScript, Ruby has both an Integer and Float class. This creates some interesting results! Let's take a look in IRB:

What happens if we do:

5 / 2
#=> 2

Have we broken Ruby? No, we have given ruby two Integers (numbers with no decimal places) so Ruby gives us an Integer back.

However, if we divide an Integer by a Float:

5 / 2.0
#=> 2.5

This is called "Type Coercion" also known as "Duck Typing"; Ruby now knows that we want a Float back.

If an object quacks like a duck (or acts like a string), just go ahead and treat it as a duck (or a string).

String interpolation

One super awesome trick that you will undoubtedly use all the time comes from our friend, the String object. It's called string interpolation – and it lets us build complicated strings without having to add them together the old fashioned way.

We used to have to do this:

first = "Ben"
last = "Franklin"
first + " " + last
#=> Ben Franklin

That works, but this is way cooler:

first = "Ben"
last = "Franklin"
"#{first} #{last}"
#=> Ben Franklin

So so useful. It works with anything – any code can run in those brackets, and it'll evaluate and turn into a string. Right??

Functions

Let's compare functions in JS and Ruby!

In Javascript

  • anonymous: function (param1, [..param2, [...]]){...},
  • named: function Name(param1, [..param2, [...]]){...}
  • uses lexical scope
  • used as values (functional programming)
  • require explicit return
  • all params are optional
  • called using parentheses ()

In Ruby

  • uses def
  • does not capture scope
  • not used as values
  • implicitly returns last evaluation
  • optional parameters must be specified
  • do not require parentheses

Examples

def say_hello
  puts "Hello, World!"
end

say_hello()

# is the same as

def say_hello
  puts "Hello, World!"
end

# note missing parentheses
say_hello

In Ruby, leaving the () off of a function call is acceptable. Since functions can't be passed as values (i.e., aren't first-class), Ruby knows that we mean to call the function, so it calls it.

Parameters (Arguments)

def say_hello(friend)
  puts "Hello, #{friend}!"
end

say_hello("Tim")
# is the same as
say_hello "Tim"

# this is an error
say_hello

# is the same as
def say_hello(friend='Tim')
  puts "Hello, #{friend}!"
end

# calling with an argument
say_hello('Jimmy')
# this is not an error any more
say_hello

Ruby functions are quite strict about how the number of arguments that can be passed. If a function expects 1 argument but we call it with 0 arguments, we will get an error. But sometimes we want to call functions without giving them all the arguments. We can do this by specifying optional arguments. If an optional argument is omitted, it simply takes a default value.

Return Values

def add(num1, num2)
  return num1 + num2
end

sum = add(2, 3)
puts "2 + 3 = #{sum}"

# is the same as
def add(num1, num2)
  # note the lack of explicit return
  num1 + num2
end

sum = add(2, 3)
puts "2 + 3 = #{sum}"

Ruby will automatically return the value of the last evaluated expression. This is called having "implicit returns". You are free to have an explicit return statement, but you don't have to.

Variables

Just like JavaScript (and literally every programming language), we're gonna need some variables to hold stuff.

Unlike JavaScript, Ruby's variables don't need to be declared.

Where you're now used to:

var genius = "me";

We can skip right to the good stuff:

genius = "me"

Important to know how to use 'em. But that's only one type of variable, and there are a few.

Types of Variables

Variables, of course, are just placeholders.

Let's talk about the different types of variables you'll encounter in Ruby. You'll need to use all of them at some point, but some more than others.

In these examples, we'll defined a variable, and then we'll write a tiny quick method that just spits that variable out, to see if it works.

Local Variable

A local variable (lower_snake_case) is a quick placeholder, and gets forgotten as soon as your method or function is over.

some_variable = "donuts"

def some_method
  some_variable
end

some_variable # => "donuts"
              # because we're using it in the same place we defined it

some_method   # Run our method, when it was defined outside that method –
              # NameError: undefined local variable [blah blah blah]

These are great when you just need to temporarily store something or quickly give something a readable variable name, but won't need it later.

Instance Variable

An instance variable (lower_snake_case) is a variable that is defined in an instance of an object. That's not meant to be a fancy term - an instance is just an example of an object, one thingy in the great world of things.

@some_variable = "donuts" # "donuts"

def some_method
  @some_variable
end

@some_variable # => "donuts"
some_method # => "donuts"

Remember that it works this way, because when we get to Objects & Methods later this week, you'll see that instance variables let us store a variable once and use it however many methods we need inside an object.

Constant

Mostly, we're able to change what a variable's holding if we so choose – constants are designed for the opposite. Constants are meant to be placeholders that never change.

SOME_CONSTANT = "donuts"
#=> "donuts"

def some_method
  SOME_CONSTANT
end

SOME_CONSTANT
#=> "donuts"

some_method
#=> "donuts"

SOME_CONSTANT = "awesome"
#=> warning: already initialized constant SOME_CONSTANT

We can use a constant anywhere in a Ruby application – inside a method, outside a method, across objects & a whole app. But keep in mind, it's meant to be defined only once, so we'll use it for things like storing application settings, or other stuff we don't intend to change.

Note that if we try to reassign a constant, the reassignment still succeeds! All the constant syntax does is give a warning on reassignment.

Ruby & ruby - Codealong

Until now, we have been running and debugging our HTML, CSS and JavaScript files using the browser. However, when using Ruby, we run our code using the command-line Ruby interpreter called ruby (with a lowercase 'r'). But don't worry, the process of writing our code and checking for errors is exactly the same!

So, let's create our first Ruby file and run it with ruby. First, let's create a new .rb file and open it with Sublime:

touch my_first_ruby_file.rb
subl .

Now, inside this file let's add:

puts "Hello, I am running Ruby with ruby!"

Pro Tip: Despite being slightly different, at this point you can think of puts as similar to console.log.

Finally, run the file using:

ruby my_first_ruby_file.rb

Great! Now let's move on to some practice using IRB.

Independent Practice

Now you try it!

Use what you just learned about Ruby data types, methods and string interpolation; hop in irb; and get through as many of the following questions as you can:

  • Declare a constant that contains your name
  • Declare a variable that contains your age
  • Write a method that accepts two parameters: an age and a name
    • This method should interpolate the age and name into a string that says, "Hi there, my name is _ and I'm __"; print the string to the screen
  • Call the method

  • Create an array my_friends and add the names of your best friends to the array

  • Write a method that accepts one parameter: list_of_friends
    • Using string interpolation, write some code in this method that will print out a list of your friends as a string. The output should be as follows: "Hi there, these are my friends: __".
  • Call the method, passing in my_friends

Conclusion

We'll get to see a lot more of Ruby over the next couple days, and the next couple weeks. Next up we're going to learn in depth about control flow in Ruby, and then working with arrays & hashes.

  • What data types does Ruby have, and what are some differences from JavaScript's types?
  • What 3 types of variables did we talk about? What do you use each one for?
  • What do you like more about Ruby so far? What do you like more about JS?

results matching ""

    No results matching ""