Ruby is a dynamic, reflective, general purpose object-oriented programming language whose syntax and language features are largely derived from Perl and Smalltalk.
Ruby has the ability to support multiple programming paradigms, including functional, object oriented, imperative and reflection. It also has a dynamic type structure and automatic memory management; it is therefore similar in varying aspects to other scripting languages such as Python, Perl, Lisp, Dylan, and CLU.
Code examples:
Classes and Methods
class Car
#Variable assignment statement.
speed = 100
#Car constructor.
def initialize(s)
speed = s
end
#Method that accepts no arguments.
def accelerate
speed += 1
end
#Method that accepts a single argument.
def accelerate(value)
speed += value
end
#Method that returns a value.
def getSpeed
return speed
end
end
Comments
#Comments start with hash
Variables
Ruby doesn't care about type, so you define a variable like this:
x = 100
or
country = "Australia"
Objects
#Creating a new object
car = Car.new
Arrays
#Array of Strings
classMembers = ["chris", "nick", "john"]
Associative arrays
# Melissa's address
melissa_addr = {
"street" => "23 St George St.",
"city" => "Silver Spring",
"state" => "MD",
"zip" => "20465"
}
#Prints one of the varables
puts melissa_addr["street"]
Input/Output:
#Puts being printline. print is print without breakline
puts "What is your name"
name = gets
#.chomp removes the return key you hit after inputing your name
name = name.chomp
puts "Hello " + name + ", how are you?"
If:
if number > 2
puts "Number is bigger than two!"
elsif number == 2
puts "Number is two"
else
puts "Number is less than two!"
end
For loop:
99.downto(1) do | i |
puts "Number is " + i.to_s
Or:
1.upto(99) do | i |
puts "Number is #{i}"
While loop:
count = 0
while count < 10
puts "count = " + count.to_s
count += 1
end
"For-each"-ish:
10.times do
puts "Hi!"
Comments