This is a very basic introduction to Ruby directed for those without much programming experience. It will cover using the terminal and interative ruby shell (IRB), data types, objects/classes, methods, conditional logic, and running a program from a file in the terminal.
Based on the workshop developed by Dessy Deskalov for Ladies Learning Code
Why do people love Ruby?
Created in 1993 by Yukihiro Matsumoto, from Japan.
“I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of the Ruby language.”
The IRB (“Interactive Ruby Shell”) is an interactive command-line interpreter that can be used to test code quickly.
Applications -> Utilities -> Terminal
(C:\windows\system32\cmd.exe)
Start -> All Programs -> Accessories -> Command Prompt
Type IRB into the console
irb
Then you’ll see somthing like this:
ruby-1.9.2-p290 :001 >
Try typing:
irb(main):001:0>puts "Hello World"
Hello World
=> nil
puts
is the basic command to print something out in Ruby.
=> nill
is the result of the expression.
Math:
> 1 + 1
=> 2
> 462 * 86
=> 39732
Numbers without decimals are called INTEGERS
. We just did some math with some integers.
Letters, words, and sentences are called STRINGS
. We tell Ruby that we are intending to use a string by wrapping it in quotes.
Some other data types in Ruby:
binary
boolean
float
decimal
What if we want to remember the result of some of this math? Assign the result to a variable.
irb(main):007:0> a = 3 ** 2
=> 9
irb(main):007:0> b = 4 ** 2
=> 16
irb(main):007:0> Math.sqrt(a+b)
=> 5.0
We can also assign a String to a variable
irb(main):007:0> my_name = "John Doe"
=> "John Doe"
Telling Ruby the variable
my_name points to the string
“John Doe”.
Everything in Ruby is an Object
.
Great, but what is an object?
An OBJECT
is an INSTANCE
of a CLASS
.
Before she can do something with an object, Ruby needs to know what kind of object
she’s dealing with.
irb(main):007:0> 1+1
=> 2
irb(main):007:0> "1" + "1"
=> "11"
Classes
define objects
and what can be done with them.
The Integer class
will have different instructions for “+” than the String class
.
Objects
have an IS A relationship with their classes
.
The actions you can perform on an object
are called methods
.
Every object
that IS A class
can perform the methods defined by that class.
irb(main):010:0> def hi
irb(main):011:1> puts "Hello World!"
irb(main):012:1> end
=> :hi
The Integer class
has instructions for the methods next, odd?, and even?.
You can call next, odd?, and even? on ALL Objects that are Integers
The String class
has instructions for the methods capitalize, upcase, and reverse.
You can call capitalize, upcase, and reverse on ALL Objects
that are Strings
.
> 99.zero?
=> false
> 99.odd?
=> true
> 99.even?
=> false
> title = "Peter Rabbit"
> title.reverse
What am I supposed to do with this object? | reverse |
Do I know how to do that action on this object? | Yes! The String class defines a method reverse and returns the string in reverse order. |
=>"tibbaR reteP"
> "universityoftoronto".capitalize
=> "Universityoftoronto"
> "universityoftoronto".upcase
=> "UNIVERSITYOFTORONTO"
> "UNIVERSITYOFTORONTO".downcase
=> "universityoftoronto"
> "universityoftoronto".reverse
=> "otnorotfoytisrevinu"
> myNumber = 123
> myNumber.reverse
What am I supposed to do with this object? | reverse |
Do I know how to do that action on this object? | No. The Integer class does not define a method reverse. |
=> NoMethodError: undefined method `reverse' for 123:Fixnum
from (irb):1
from :0
How can I find the class of my object?
> mysteryObject = "What am I?"
> mysteryObject.class
=> String
How do I know what methods I can call on my object?
> mysteryObject.methods
=> ["upcase!", "zip", "pretty_print_cycle"....]
How do I know what those methods do?
Look them up here
Ruby comes with many built-in classes that we can use.
String
, Integer
, File
, Hash
, Array
…
You can read about all the built-in objects here
What if we want to define our own class?
Let’s return to the method
hi we wrote (and improve it)
irb(main):010:0> def hi(name)
irb(main):011:1> puts "Hello #{name}!"
irb(main):012:1> end
=> :hi
The method
hi takes the name as a parameter
.
#{name}
is Ruby’s way of inserting something into a string
irb(main):024:0> class Greeter
irb(main):025:1> def initialize(name)
irb(main):026:2> @name = name
irb(main):027:2> end
irb(main):028:1> def say_hi
irb(main):029:2> puts "Hi #{@name}!"
irb(main):030:2> end
irb(main):034:1> end
=> nil
The new keyword here is class
. This defines a new class called Greeter and a bunch of methods for that class. Also notice @name
. This is an instance variable, and is available to all the methods of the class. As you can see it’s used by say_hi
.
Lets create a Greeter object and use it:
irb(main):035:0> greeter = Greeter.new("Pat")
=> #
irb(main):036:0> greeter.say_hi
Hi Pat!
=> nil
The method new
is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods. The initialize
method is a special type of method, which will be executed when the new
method of the class is called with parameters.
Let’s make a class Calculator
that has the methods add
and subtract
irb(main):035:0> my_calculator = Calculator.new
=> #
irb(main):036:0> my_calculator.add(5,2)
7
=> nil
irb(main):036:0> my_calculator.subtract(5,2)
3
=> nil
irb(main):024:0> class Calculator
irb(main):025:1> def add(x,y)
irb(main):026:2> puts x + y
irb(main):027:2> end
irb(main):028:1> def subtract(x,y)
irb(main):029:2> puts x - y
irb(main):030:2> end
irb(main):034:1> end
=> nil
Open any text editor, add the same code, and save it as twitter.rb. Remember the directory you have saved it in.
tweet = "I'm writing my first program and it's pretty rad."
puts tweet.length
To run your program, type quit to exit from IRB, and then type:
ruby twitter.rb
Asks you to type something.
Tells you how many characters you’re working with.
So far, we’ve just been putting our tweet directly into the program.
The puts method
is used for output, and the gets method
is used for input. Try this:
The gets method
warns Ruby that you’re about to speak.
> tweet = gets
all-string
I'm learning Ruby with #ladieslearningcode
=> "I'm learning Ruby with #ladieslearningcode\n"
Wait, we didn’t type \n in our tweet. What is that?
The \n is there because you hit the enter button after you typed your tweet. It represents a new line, and counts as exactly one character. To get rid of it, do this:
> tweet = gets.chomp
all-string
I'm learning Ruby with #ladieslearningcode
=> "I'm learning Ruby with #ladieslearningcode"
Now try this:
> tweet = gets.chomp
all-string
I'm a lady learning code with @learningcode #ladieslearningcode
=> "I'm a lady learning code with @learningcode #ladieslearningcode"
> puts tweet
all-string
I'm a lady learning code with @learningcode #ladieslearningcode
=> nil
Working with your group, modify your Twitter program to do the following:
Ask (politely!) for a tweet from the user.
Store the tweet in a variable, without \n
Output the tweet the user gave.
Output the number of characters in the tweet.
Output how many more characters the user can add until they hit 140 characters.
(answers in assignments/twitter_3.rb)
Twitter…
Lets you send your tweet if it is 140 characters or less
Tells you that your tweet is too long to send otherwise.
So far we know how to determine the length of the user’s tweet.
We don’t know how to tell them whether they can or cannot send their tweet, depending on it’s length.
Programming is writing out sets of simple instructions for the computer to follow.
Let’s break down out tweet logic into simple instructions.
We want our program to …
if the tweet is greater than 140 characters, tell the user that they cannot send their tweet
if the tweet is less than or equal to 140 characters, tell the user that they can send their tweet
Logical operators
> 200 > 140
=> true
> 200 < 140
=> false
Try the code below in IRB:
>if 200 > 140
> puts true
>end
=> true
Try the code below in IRB:
>if 200 > 140
> puts true
>else
puts false
>end
=> true
tweet = gets.chomp
if tweet.length <= 140
puts "Tweet your heart out!"
end
tweet = gets.chomp
if tweet.length <= 140
puts "Tweet your heart out!"
else
puts "Your tweet is too long!"
end
What if you want to be able to tell your program when to stop running? Create a new program with the following code.
puts "Hi!"
greeting = gets.chomp
while greeting != "bye!"
puts greeting
greeting = gets.chomp
end
This is called a while loop. The program will run while the user inputs anything other than “bye!”
[1, 2, 3, 4, 5]
[7, 13, 14, 16, 14, 48]
["ladies", "learning", "code"]
> my_numbers = [1, 2, 3, 4, 5]
> my_numbers.each do |i|
> puts i**2
> end
Inspired by Chris Pine’s Learn to Program
And finally…