Ruby is an interpreted programming language, so it needs a VM (virtual machine) as the middleman.
It can be run on the command line with
ruby my_program.rb
Or you can use a REPL (“Read, Evaluate, Print, Loop) like IRB by running
irb
Variables:
Variables need not be declared.
a = 5 # 5
Variables are evaluated right side first.
Flexible Typing
c = 20 # 20 c= "hello" # "hello"
Naming conventions:
- start with lowercase letter
- no spaces
- no special characters (eg: $, @, &)
- use snake case
- names after meaning rather than type of content
- not abbreviated
Strings
To get a substring:
greeting = "Hi everyone" greeting[0..4] # Hi ev
Similar to JS, -1 indicates the last position in the string
.split without an argument splits by space (” “).
An argument can be passed in, like: .split(",")
.sub("term", "replacement term") replaces a single occurrence
.gsub("term", "replacement term")(global substitute) replaces all occurrences
String concatenation
"Hello, " + name + "!"
String interpolation
(only works with double quotes)
"Hello, #{name}!"
Symbols
Symbols can be thought of as “named integers”. It doesn’t matter what the actual value the symbol references. Any reference to that value within the VM will give back the same value, and their value cannot be changed.
Symbols start with a colon and then letters.
:flag
Why use symbols?
From rubylearning:
A Symbol is the most basic Ruby object you can create. It’s just a name and an internal ID. Symbols are useful because a given symbol name refers to the same object throughout a Ruby program. Symbols are more efficient than strings. Two strings with the same contents are two different objects, but for any given name there is only one Symbol object. This can save both time and memory.
Numbers
There are two types: integers and floats
Integers are easier to work with.
You can use math operations like: +, -, /, *
In Ruby, integers are objects with methods.
So a for-loop looks like this:
5.times do
puts "Hello, World!"
end
.rand generates a random float from 0.0 to 0.1.
.rand(101) generates a random integer from 0 to 100
The Math object has similar methods in Ruby to JavaScript:
puts(Math::PI) puts(Math::E) puts(Math.cos(Math::PI/3)) puts(Math.tan(Math::PI/4)) puts(Math.log(Math::E**2)) puts((1 + Math.sqrt(5))/2)
Blocks
Bracket blocks
5.times{ puts "Hello, WOrld!" }
There are many methods that accept blocks, like .gsub
"this is a sentence".gsub("e"){ puts "Found an E!"}
Block parameters
If the instructions within a block needs to reference a value we’re working with, we can pass it in inside the block parameter:
5.times do |i|
puts "#{i}: Hello World!"
end
"this is a sentence".gsub("e"){|letter| letter.upcase}
A function with a parameter looks like this:
def sayMoo numberOfMoos puts 'mooooooo...'*numberOfMoos end
Calling the function looks like this:
sayMoo 3
Arrays
Arrays in Ruby are pretty similar to JavaScript.
meals = ["Breakfast", "Lunch", "Dinner"]=> ["Breakfast", "Lunch", "Dinner"]meals "Dinner"meals.last=> "Dessert"
You add an element with the shovel operator “<<".
There are useful methods like .last
.sort returns the array sorted by alphabetical or numerical order (depending on whether they are strings or numbers).
There is also .each, .join, index (which finds the index of the element), include?, etc…
More methods here: http://ruby-doc.org/core-2.1.2/Array.html
Hashes
Hashes in Ruby is similar to Objects in JavaScript. It’s a collection of key value pairs.
produce = {"apples" => 3, "oranges" => 1, "carrots" => 12}
puts "There are #{produce['oranges']} oranges in the fridge."
Keys and values are linked by the rocket symbol “=>”.
produce["grapes"] = 221
Assignment is the same as in JavaScript.
Hash syntax
Symbols are commonly used as keys of a hash. When all the keys are symbols, you can omit the hash.
produce = {apples: 3, oranges: 1, carrots: 12}
puts "There are #{produce[:oranges]} oranges in the fridge."
Conditionals
Conditional operators are: == (equal), != (not equal to), > (greater than), >= (greater than or equal to), < (less than), <= (less than or equal to), etc…
Other conditional operands:
(returns 0 if equal, 1 if first operand is greater than the second, and -1 if the first operand is less than the second).
=== (Used to test equality within a when clause of a case statement)
.eql? (True if the receiver and argument have both the same type and equal values)
.equal? (True if the receiver and argument have the same object id)
Conditional branching
def water_status(minutes)
if minutes < 7
puts "The water is not boiling yet."
elsif minutes == 7
puts "It's just barely boiling"
elsif minutes == 8
puts "It's boiling!"
else
puts "Hot! Hot! Hot!"
end
end
Only one section of the if/elsif/else structure can have its instructions run. If the if is true, Ruby will never look at the elsif.
You can also use ‘if’ inline:
$debug = 1 print "debug\n" if $debug
Other conditional statements here
There are “or”, “and” and “not” in Ruby, with a lower precedence than “||”, “&&” and “!”. You can find the precedence table here
nil is nothingness, similar to JavaScript’s undefined
Class
class Student
attr_accessor :first_name, :last_name, :primary_phone_number
def introduction(target)
puts "Hi #{target}, I'm #{first_name}!"
end
end
To create an instance of the class:
frank = Student.new
frank.first_name = "Frank"
//To call the introduction method
frank.introduction('Katrina')
puts and gets
puts (put string) is equivalent to console.log
gets (get string) takes in user input
gets.chomp removes any ‘Enters’ from the end of string
String methods
There are the usual, like:
.upcase, .downcase, .capitalize, .swapcase
There’s also others, like .center:
lineWidth = 50
puts( 'Old Mother Hubbard'.center(lineWidth))
puts( 'Sat in her cupboard'.center(lineWidth))
puts( 'Eating her curds an whey,'.center(lineWidth))
puts( 'When along came a spider'.center(lineWidth))
puts( 'Which sat down beside her'.center(lineWidth))
puts('And scared her poor shoe dog away.'.center(lineWidth))
And .ljust, .rjust:
lineWidth = 40 str = '--> text <--' puts str.ljust lineWidth puts str.center lineWidth puts str.rjust lineWidth puts str.ljust(lineWidth/2) + str.rjust(lineWidth/2)
Following tutorial here and here
Resources: Pragmatic programmer’s guide to ruby