miércoles, 2 de julio de 2014

Brief introduction to Ruby syntax

Ruby is very much a “There’s more than than one way to do it” type go language, in the same vain as Perl but quite different in philosophy from languages such as Python



You can also execute Ruby commands directly from the command line using -e:

ruby -e “puts 2 + 2”
One Unix-related platforms it’s possible to add a “Shebang” line as the first line of Ruby scripts so that it can be exe cued without having to invoke the Ruby interpreter explicitly. For example:

########################

#!/usr/bin/ruby
puts “Hello World”

########################


Interactuve Ruby

Ruby has an interpreter called irb

We can invoque rib from the command line and the results of your code are given as son as you type it

EXPRESSIONS, LOGIC, AND FLOW CONTROL

Basic Expressions
Ruby supports expressions in a style familiar to almost any programmer:

########################

“a” + ”b” + ”c”

->> abc

########################


To change the type of the variable the is a method called .to_s / .to_i / .to_f


########################

“20”.to_i + 10

->> 30


“20” + 10.to_s

->> 2010

########################

Comparison Expressions
In some situations comparisons might return bill, Ruby’s concept of “null” or nonexistence

########################

2 == 1 

->> false

2 == 1

->> true

(2 == 2) && !(1 ==  2)

->> true

puts “The universe is broken” if 2 == 1

# On C style

if (2 == 1 )
puts “The universe is broken”
end

########################

Ruby also supports the else directive, as found in languages such as C, Pearl, and Pascal:

########################

if 2 == 1
puts “The universe is broken!”
else
puts “The universe is OK”
end

if x == 1 || x == 3 || x == 5 || x == 7 || x == 9
puts “X is odd and under 10”
elseif x == 2 || x == 4 || x == 6 || x == 8
puts “X is even and under 10
else
puts “X is over 10 or under 1”
end

########################

Note C coders will be used to else if. Ruby’s variation is based on the Perl standard of elseif.

Case sentence

########################

fruit = “Orange”
case fruit
when “orange”
color = “orange”
when “apple”
color = “red”
when “banana”
color = “yellow”
else 
color = “Unknown”
end

########################

Case is essentially, a substitution for a large, messy clump of if and elseif statement


THE TERNARY OPERATOR (CONDITIONAL EXPRESSIONS)

########################

x = 10
puts x > 10 ? “Higher than ten” : “Lower or equal to ten”

->> Lower or equal to ten

########################

The ternary operator works like so:

expressions ? true_expression : false_expression

LOOPS

########################

 i = 0
loop do
i += 1
break if i > 100
end

########################

Note: 
variable += 1 is the same of variable ++ or variable = variable + 1

########################

i = 0
while ( i < 15 )
i += 1
next if i % 2 == 0
puts i
end

########################


OBJECT ORIENTATION:

OBJECTS

The key difference between Ruby and most other major object-oriented languages  is that in Ruby everything is and object

function1(function2(function3(something)))

in Ruby the correct syntax is

something.function3.function2.function1


CLASSES AN METHODS:

Class variables begin with two @ signs and exist within the scope of a class and all its objects

########################

class Person
@@count = 0

def initialize
@@count += 1
end

def Person.count
@@count
end
end

a = Person.new
b = Person.new
c = Person.new
puts Person.count

->> 3

########################

REFLECTION:

Reflection is a process that allows a computer program to observe an modify its own structure and behavior during execution

########################

Hash.methods

########################


You can also use methods to retrieve a list of class methods, because class ore also objects in Ruby

METHOD VISIBILITY:

Methods can be 
public (callable by any scope within the program), 
private (callable only within the scope of the instance the methods exist upon)
protected (callable by any object of the same class)

########################

class MyClass
def public_method
end

private
def private_method1
end

def private_method2
end

protected
def protected_method
end
end

########################

Regular Expressions

########################

“this is a test”.sub(/[aeiou]/, ‘ * ’ )

->> th*s is a test

“This is a test”.gsub(/[aeiou]/, ‘ * ‘ )

->> Th*s *s * t*st

“THIS IS A TEST”.gsub(/[aeiou]/, ‘ * ‘ )

->> THIS IS A TEST

“THIS IS A TEST”.gsub(/[aeiou]/i, ‘ * ‘ )

->> TH*S *S * T*ST

########################


sub performs a single substitution based on a regular expression, whereas gsub performs a global substitution, you use /i option to make the regular expressions case insensitive

########################

“This is a test”.scan(/[aeiou]/)

->> [‘i’,’i’,’a’,’e’]

########################

NUMBERS:

You can produce roots easily by raising a number to the power of 1/n For example, you can fine the square root of 25 with 25 ** 0.5

When you use a number the class of default is integer, so if you need to use float numbers is precise to indicate the conversion 10.to_f or 10.0 or Float(10) 

ARRAYS:

Arrays are ordered collections of OBJECTS, because everything in Ruby is an object! Arrays can contain any combination of objects of any class

Example shows the invocation of the Array class’s push method:

########################

a = []
a.push(10)
a.push(‘test’)
a.push(30)
a << 40

->> [10, ’test’, 30, 40 ]

########################

Notice the use of a different from pushing objects to an array with the << operator on the last line of the preceding example

HASHES (ASSOCIATIVE ARRAYS):

########################

fred = {
‘name’ => ‘Fred Eliot’,
‘age’ => ’63’,
‘gender’ => ‘male’,
‘favorite painters’ => [‘Monet’, ‘Contable’, ‘Da Vinci’ ]
}

puts fred[‘age’]

->> 63

puts fred[‘favorite painters’].first

->> Monet

########################

COMPLEX STRUCTURES:

########################

people = {

‘fred’ => {
‘name’ => ‘Fred Eliot’,
‘age’ => ’63’,
‘gender’ => ‘male’,
‘favorite painters’ => [‘Monet’, ‘Contable’, ‘Da Vinci’ ]
},

‘janet’ => {
‘name’ => ‘Janet S Porter’,
‘age’ => ’55’,
‘gender’ => ‘female’,
}
}

puts people[‘fred’] [‘age’]
puts people[‘janet’][‘gender’]
puts people[‘janet’].inspect

->>
63
frmale
{‘name’ => ‘Fred Eliot’,‘age’ => ’63’,‘gender’ => ‘male’}

########################

FILES:

Here is the traditional way you’d open and read a file (as when using a more procedural
lenguages)

########################

lines = []
file_handle = file.new(“/file/name/here”, “r”)

while line = file_handle.gets
lines << line
end

########################

In Ruby is everything more simple

########################

lines = File.readlines(‘/file/name/here’)

########################


DATABSES:

The are several ways to connect to database system such as MySQL, PostgradeSQL, Oracle, SQLite, and SQL server from Ruby. Typically a “Driver” library is available for each of the main database system, although these don’t come with Ruby by default. You typically install database driver libraries using the Ruby Gems, Ruby library packaging system, or you might need to download and install them manually.

FILE ORGANIZATION:

The simplest way to create a library is to create a Ruby file containing classes and methods and use require to load it


########################

class MyLib
def MyLib.hello_world
puts “Hello World!”
end
end

########################

And then you have another file like so:

########################

require ‘mylib’
MyLib.hello_world

########################


PACKAGING:


Any gem files uploaded to Ruby projects hosted on the RubyForge site are made available in the default repository, making a RubyForge account a necessity if you want to distribute your libraries to the widest audience possible in an easy fashion .

No hay comentarios:

Publicar un comentario