For beginners
Learn ruby by examples
Assumptions
Requirements
# initialize a variable, name, to hold a value "Sarah":
name = "Sarah"
# print name to the screen
puts name
# ask for user's age, read the input and save it to
# a variable "age":
age = gets
# define a method called 'say_hi' that takes an argument, name
# and prints a greeting:
def say_hi(name)
puts "Hi #{name}"
end
# instance variable: the name of the instance variable starts
# with '@', once the variable is defined, you can use it any
# where in your class:
@country = "USA"
# constant variable: constant variable's name is always in
# uppercase, once constant variable has been initialized
# it's value will not be changed
SSN = "1234567890"
# array: array is a collection of elements,
# it's always good to use only one type in an array,
# for example all strings, or all integer:
my_arr = ["a", "b", "c", "d", "e", "f", "g"]
# you can access elements in the array via their index,
# array always starts at index 0
my_arr[5] # "f"
my_arr[1] = "z" # ["a", "z", "c", "d", "e", "f", "g"]
# conditions:
if(condition)
do_something
elsif(another_contidion)
.
.
.
else
do_something
end
# some conditions:
if(x == y) # if x and y are assert_equal
if(x < y) # if x is less than y
if(x <= y) # if x is less than or equal to y
if(x > y) # if x is greater than y
if(x >= y) # if x is greater than or equal to y
if(something) # when the value of something is true
if(!something) # when the value of something is false
# Loop - in order to run a block at least once, you can use
# begin/while loop:
begin
do_something
end while(some_condition)
Some great tools and websites to learn ruby: