Ruby is an object-oriented programming language, designed to make programmers happy. It has a lot of syntactic sugar that makes Ruby easy to read and fun to learn! In my opinion, Ruby is a great first language for baby code witches!
I'm no technical writer (I'll leave that to my husband, @docswarlock), but let me give you a quick rundown of some Ruby basics.
We use variables to store and retrieve data. Think back to your high school algebra class. Ruby variables work in much the same way.
Ruby variables are declared using the assignment operator, also known as the equal sign (=). The variable name goes to the left, and the value is placed on the right.
# the variable, x, equals the value, 1234.
x = 1234
If you need to declare a constant, simply begin your variable name with a capital letter. It is common convention to use all caps for constants.
Constant = "I'm a constant."
BETTERCONSTANT = "I'm a constant that follows conventions."
Ruby methods, similar to functions in other languages, let you reuse chunks of code. Once you define a method, you can call it in other areas of your program!
To define a method, use the keyword
def , followed by the method's name.
It is good practice to name your method in a way that describes its purpose.
Close the method definition with the keyword
puts "Hello World"
To invoke a method, simply say the method's name.
# Let's invoke our previous method.
=> "Hello World"
Two common data structures in Ruby are arrays and hashes. Both...
- allow you to store multiple multiple data points in one location.
- can contain any type of data, including other arrays and hashes
- can be looped or iterated through with various helper methods
Let's look at an array:
# An array is surrounded by square brackets.
# Each element is separated by a comma.
[ "This", "is", "an", "array", 1, true, false ]
Let's look at a hash:
# An array is surrounded by curly brackets.
# Data is stored in key: value pairs.
# These pairs are separated by commas.
key_with_array_value: ["another", "array"],