Ruby is a programming language with the following properties:
It was created in 1995 by Yukihiro Matsumoto.
Ruby is a programming language with the following properties:
It was created in 1995 by Yukihiro Matsumoto.
To print out "Hello World" the console:
puts "Hello World"
'Puts'is short for put string. It ends with a newline (\n) returns undefined.
Variables are declared without needing to explicitly define the type. It is clear to ruby what type the variable is from how you declare it
a = "I am a string"
b = 3 #Fixnum
c= 3.3 #Float
Everything in ruby is an object - which means that each time you declare a variable as in the case above, these variables have access to a wide variaty of methods inherant in the type of object that is instantiated as.
There are four levels of variable scope:
g = "I am a global variable" #defined outside of any Function
def someFunction
l = "I am a local variable" #can only be accessed from within the function
end
def class MyClass
@@class_var = "I am a class variable" #Available to any instantiation of the class
def classFunction
@instance_var = "I am an instance variable" #Available to every function within an instance of the class
end
end
A Ruby constant is like a variable, except that its value is supposed to remain constant for the duration of the program. The Ruby interpreter does not actually enforce the constancy of constants, but it does issue a warning if a program changes the value of a constant.
A_CONSTANT = "I am a constant"
Ruby knows that you have declared a constant from the all caps declaration.
These are the basic data types in ruby:
s = "I am a string"
fixnum = 3 #number Fixnum (integer)
float = 3.3 #number Float
array = ["a", 1, 2, "hello"] #Array
hash = {name: "Robin", lastName: "Bson"} #Hash
s = :unique #Symbol
I_Am_True = true #bolean
Then there are blocks which as far as I know is unique to ruby:
{puts "Hello yo"}
#or
do
puts "Hello yo"
end
# Pass block to function without having to define it as a function parameter (called when yielded)
def f
yield
end
f {puts "I am a block"} # => I am a block
If statements:
if x > 2
puts "x is greater than 2"
elsif x < 2
puts "x is less than 2"
else
puts "x is 2"
end
While loop:
while true
puts "Infinite loop"
end
For-loop
for i in (1..5)
puts i
i += 1;
end
#same result
(1..5).each {|i| puts i}
Declaring and using a function is simple enough:
def quad(x)
x**4
end
quad(4) # => 256
Notice abscence of return-keyword. A ruby function/method returns the last line of the function by default
This site has been made to practice writing technical doucumentation pages. For a complete guide on the ruby languate i recommend Ruby-doc.org.