An object-oriented programming language, based on C. With the popularization of the Rails platform, Ruby has been a favorite of programmers who want to develop apps quickly.
> puts "Hello, Universe."
"Hello, Universe."
=> nil
Open up Terminal/Command Prompt, and type in "irb".
puts will print your message to the screen. Whether it be text or a number. It also gives you a line break.
print will do the same, but without the line break:
> print "Good luck, kid. You're gonna need it."
"Good luck, kid. You're gonna need it."
=> nil
$ irb
>
Let's print out our first message:
String - a sequence of text enclosed in '' or ""
example: "This is a string."
Integer - whole numbers
Float - numbers with decimal values
Boolean - true or false
Array - an ordered list of items
example: items = ['item1'. 'item2', 'item3']
Hash - an unordered collection of key/value pairs
example: cars = {'Ford' => 'Mustang', 'Bugati' => 'Veyron', 'Fiat' => 'Arbath'}
Strings are text captured within quotation marks.
A String can be a word, or a sentence, or several sentences.
#this is a string:
my_string = "Nah"
#and so is this:
my_other_string = "Nah nah nah nah nah nah nah nah nah nah nah, hey Jude.
Nah nah nah nah nah nah nah nah nah nah nah, hey Jude.
Nah nah nah nah nah nah nah nah nah nah nah, hey Jude."
You can also think of a String as a set of characters. And you can pull an individual character by it's index (or, it's placement within the String).
The index is a number between 0 and one-less-the-length of the String, captured in square brackets ([]).
> my_string = "Oh what a lovely String this is."
> puts my_string[11]
=> r
Strings have several "methods" attached to them that help you search through and modify them.
> my_string = "the best string ever!"
> my_string.reverse
=> "!reve gnirts tseb eht"
> my_string.capitalize
=> "The best string ever!"
> my_string.upcase
=> "THE BEST STRING EVER!"
> shouting = "ARE WE HAVING FUN YET?"
> shouting.downcase
=> "are we having fun yet?"
> shouting.length
=> 22
> shouting[0..13]
=> "ARE WE HAVING "
Creating and assigning variables in Ruby is super simple! You don't have specify, like you do in other programming languages, which data type you want the variable to be. Ruby is smart enough to recognize a data type on its own!
#a string:
sentence = "I love Ruby, and I don't care who knows it!"
#Ruby knows it's a string because of the quotation marks
#an integer:
my_number = 42
# Ruby knows it's an integer because it's a whole number
# (no decimal point and value afterwards)
#a float:
my_other_number = 15.16
# Ruby knows it's a float because
# there's a decimal point and value afterwards
#a boolean:
the_truth = false
# Ruby knows it's a boolean because it's either true or false
# (and no quotation marks!)
When it comes to naming variables, you should use all lowercase letters. If you want the variable name to be two or more words, use an underscore ( _ ) between the words:
Variable names can contain a number, but they must start with a letter:
whats_up = "not much"
my_fav_number = 23
where_2_go = "the beach"
number4 = 8.15
To run a Ruby program:
$ ruby firstprogram.rb
Hello Universe
$
gets is the command that actually takes the input, w/ a line break.
.chomp is a function that works on gets that removes the line break.
puts "What's your name?"
name = gets.chomp
puts "Oh, hi " + name
$ ruby firstprogram.rb
What's your name?
Mr. Roboto
Oh, hi Mr. Roboto
$
An important piece of info: gets.chomp takes any input as a String data-type.
When printing out a variable attached or within a String, there are two schools of thought:
#concatenation uses the + sign to add strings and variables together
> age = "24"
> puts "Today I am " + age + "-years-old."
=> "Today I am 24-years-old."
#but with concatenation, the variable must be a String!
Concatenate!
Interpolate!
#interpolation uses the symbols #{} to plop a variable inside a string.
> age = 58
> puts "Yesterday I turned #{age}-years-old!"
=> "Yesterday I turned 58-years-old!"
#with interpolation you can use any data type!
Sometimes, you just need a variable to be something it's not.
That's when it's time to convert the data type!
These methods are especially handy when dealing with gets.chomp.
.to_s - To String
.to_i - To Integer
.to_f - To Float
#Converting a string to an integer:
my_number = "1"
my_number.to_i
#so now my_number = 1, no quotation marks
#Converting integer to string:
my_number = 2
my_number.to_s
#now my my_number = "2"
#Converting integer to float:
my_number = 3
my_number.to_f
#now my_number = 3.0
While Ruby is pretty darn smart in general, it needs to be told when a conditional statement is over, so you must put "end" when your statement is complete.
Here's a more fleshed-out example:
if sum == 13
puts "Wait...the lucky 13 or the unlucky 13?"
else
puts "Phew! For a second I thought it was gonna be 13."
end
if sum == 13 #If the statement 'the value of the variable sum equals 13' is true
#perform some action
else #If that statement above is false
#perform some other action
end
Equals
==
Does Not Equal
!=
Less Than
<
Less Than or Equal To
<=
Greater Than
>
Greater Than or Equal To
>=
Guessing Game: user provides number (between 1 and 10), if number stored in program same, "Wow!", else, "Dang!"
Dog Says Cat Says: ask user to enter 'dog' or 'cat', program prints animal's sound
Let's try out some examples...
Ask user for their number grade, if the grade is at least 60, tell them they passed! If it's lower than 60, tell them they have to take the class again.
Maybe you want to give your program more choice. You can add as many else ifs (written in Ruby as elsif) in between your if and else.
if answer == "do"
puts "May the Force be with you."
elsif answer == "do not"
puts "Too old. Yes, too old to begin the training."
elsif answer == "try"
puts "There is no try."
else
puts "Mudhole? Slimy? My home this is!"
end
Let's update the "Dogs Says Cat Says" program...
Sometimes you want two conditions to be met before you perform a task. This is where AND and OR come in handy.
AND is written as two ampersands ( && ), OR is written as two pipes ( || ).
Note that you need to make the comparison on both sides of the && or ||.
if sum > 13 && sum < 26
puts "Right in the sweet spot."
else
puts "Too little, too much."
end
if choice == "cash" || choice == "credit"
puts "Thanks for shopping at our store."
else
puts "Sorry, we don't accept checks."
end
There is an alternative to the if/elsif/else structure: the case conditional.
case is probably better learned from show than tell, so let's look at an example:
#we have a variable called 'option' that we want to test
case option
when 1 #when option == 1
#do something
when 2 #when option == 2
#do something else
else
#do a third thing
end
You can use the && and || specifiers with case, too.
There's is no specific time when you should use case over if/else - it is merely a matter of preference. For this class, sticking to the if/else structure is probably easiest.
Loops take certain parameters and then perform actions for as long as those parameters are true. Like conditionals, loops must be closed with end
Does exactly what it sounds like:
do something some value of times.
3.times do
puts "Beetlejuice"
end
.times Loop
You can also use a variable:
num = 4
num.times do
puts "Something clever."
end
This loop only takes integers! A string has no a numerical value, and how exactly would you suggest performing an action 4.5 times?
Print out "I think I can" 5x!
Ask the user if they're famous; if they are, print "OH MY GOD!" 10x. If not print "STRANGER DANGER!" 3x.
Practice Problems:
In an until loop, a variable is incremented and decremented, and an action is performed until a certain condition true.
num = 1
until num == 10
puts num
num += 1
end
While we loop, we increment the variable, so that 'num' will eventually equal 10.
Otherwise, we've created an infinite loop, and will just be printing "1" forever.
Practice the until Loop!
Let's try out some examples...
Ask the user for a number (1-10), print the doubles of their number through 10.
(Make sure you include the double of 10!)
Until Dad says yes, keep asking him if we can go to Itchy and Scratchy Land.
(there's a bit of a trick to this one)
Now reverse it! Ask for again for a number between 1 and 10, then count down to 0.
The while loop is pretty similar to the until loop, just testing the parameters in a different way.
Let's convert the above until loop into a while loop:
while num < 10
puts num
i += 1
end
Let's do some practice loops that utilize 'while'!
Write a loop that continues to display random numbers between 1 and 10 until the number generated is 7.
Introduce yourself as a new person until Amanda is introduced.