jueves, 10 de julio de 2014

Make a quick Ruby app


THE FIRST APPLICATION ON RUBY
I'm starting to develop on Ruby, so the best way to undertand something is try to explain 

The Application: A Text Analyzer

Requirements, Basic features:

Character count
Characters count (excluding spaces)
Line count
Word count
Sentence count
Paragraph count
Average number of words per sentence
Average number of sentence per paragraph


Building the basic application:

When starting to develop a new program it’s useful to think of the key steps  involved.

In the  past it was common to draw flow charts to show how the operation of a computer program would flow, but it's easy to experiment, change things about, and remain agile with modern tools such as Ruby. Let's outline the basic steps as follows:

1.-Load in a file containing the text or document you want to analyze
2.-As you load the file line by line, keep a count of how many lines were (one of your static taken care of)
3.-Put the text into a string and take the measure the length to get your character count.
4.- Temporarily remove all whitespace and measure the length of the resulting string to get the characters count excluding the whitespace
5.-Split out the whitespace to find how many words there
Are
6.-Split on full stops to find out how many sentence there are
7.-Split on double newlines to find out how many paragraphs there are
8.-Perform calculations to work the avarenges


Step 1
Obtaining some Dummy text
We can find the text at http://rubyinside.com/book/oliver.txt

Step 2
Load the text files and counting lines

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

#analyzer.rb first approximation

#Starts in zero
Count = 0
#load the file line by line
File.open("oliver.txt").each { |line| line_count += 1 } 
#Prints the count of the lines
Puts line_count

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

Then we look for a way to read the text, so we have to alternatives

File.open vs File.readlines, in the first aprox. I'm going to use File.open and read all the lines, at the end of the tuturial I'm going to change to File.readlines, readlines method has already the functions to count the lines

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

#analyzer.rb second approximation
#Adding a variable to collect the lines together as one as we go


Text = ' '
Count = 0
File.open("oliver.txt").each do |line|
Lines_count += 1
Text << line
End

Puts "#{line_count} lines"

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

Remembering that using {and} to surrond blocks is the standard
style for single-line blocks, using "do" and "end" is preferred for
multiple blocks.

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

#analyzer.rb third approximation
#Text is a string, we can use the length method that all strings
#supply to get the exact of the file, and therefore the number of
#chacrters, and then in other variable exclude the spaces

Text = ' '
Count = 0
File.open("oliver.txt").each do |line|
Lines_count += 1
Text << line
End
Total_characters = text.length
#using gsub to eradicate the spaces from your text string in the
#same way, and then use the length of the newly "de-spacfied"
#text
Total_characters_nospaces = text.gsub(/\s+/, '').lenght
Puts "#{line_count} lines"
Puts "#{total_characters_nospace] characters excluding spaces"
Puts "#{total_characters} Total characters"

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


Counting Words
1.- count the number of groups of contiguous letters using scan
2.- Split the text on whitespace and count the resulting fragments using split and size

To get the number of words in the string, I can use the length or size array methods to count the number of elements rather than join them together:

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

Puts "this is a test".scan(/\w+/).length

->> 4

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

The split approach demostrates a core tenet of Ruby (as well as some other languages, particulary Perl): ther's more than one way to do it! Analyzing different methods to solve the same problem is a crucial part of becoming a good programmer, as different methods can vary in their efficacy.

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

Puts "this is a test".split.length

->> 4

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




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

#analyzer.rb fourth approximation
#Counting words

Text = ' '
Count = 0
File.open("oliver.txt").each do |line|
Lines_count += 1
Text << line
End
Word_count = text.split.length
Total_characters = text.length
Total_characters_nospaces = text.gsub(/\s+/, '').lenght


Puts "#{line_count} lines"
Puts "#{total_characters_nospace] characters excluding spaces"
Puts "#{total_characters} Total characters"
Puts "#{word_count} words"

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


COUNTING SENTENCE AND PARAGRAPHS

Rather than splitting on whitespace, sentence and paragraphs have different split criteria.
Sentences end with full stops, question marks, and exclamation marks. They can also be separated with dashes and other punctuation.

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

#for end regular expressions
Sentence_count = text.split(/\.|\?|\!/).length

#For double space
Puts text.split(/\n\n/).length

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


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

#analyzer.rb fiveth approximation
#Counting paragraphs and sentences

Text = ' '
Count = 0
File.open("oliver.txt").each do |line|
Lines_count += 1
Text << line
End
Word_count = text.split.length
Total_characters = text.length
Total_characters_nospaces = text.gsub(/\s+/, '').lenght
Sentence_count = text.split(/\.|\?|!/).length
Paragraph_count = text.split(/\n\n/).length

Puts "#{line_count} lines"
Puts "#{total_characters_nospace] characters excluding spaces"
Puts "#{total_characters} Total characters"
Puts "#{word_count} words"
Puts "#{sentence_cunt} sentences"
Puts "#{paragraph_count}  paragraphs"

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

Calculating avarages

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

#analyzer.rb sixth approximation
#Counting avarages

Text = ' '
Count = 0
File.open("oliver.txt").each do |line|
Lines_count += 1
Text << line
End
Word_count = text.split.length
Total_characters = text.length
Total_characters_nospaces = text.gsub(/\s+/, '').lenght


Puts "#{line_count} lines"
Puts "#{total_characters_nospace] characters excluding spaces"
Puts "#{total_characters} Total characters"
Puts "#{word_count} words"
Puts "#{sentence_count / paragraph_count} sentences per paragrapg (avarage)"
Puts "#{word_count / sentence_count } words per sentences (avarage)"

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

The code:

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

#analyzer.rb 



#Open file and read it
lines = File.readlines("oliver.txt")
line_count = lines.size
text = lines.join

word_count = text.split.length
total_characters = text.length
total_characters_nospaces = text.gsub(/\s+/, '').lenght


puts "#{line_count} lines"
puts "#{total_characters_nospace] characters excluding spaces"
puts "#{total_characters} Total characters"
puts "#{word_count} words"
puts "#{sentence_count / paragraph_count} sentences per paragrapg (avarage)"
puts "#{word_count / sentence_count } words per sentences (avarage)"

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



martes, 8 de julio de 2014

10 mentiras que las mujeres dicen los hombres y sus motivos




La mentira: "Me duele la cabeza"
Mentira Similares: 'Estoy cansada' 

La verdad: "Yo realmente no estoy de humor para esto."

¿Por qué dicen está mentira? A veces, simplemente realmente no sienten ganas de hacer algo. Un dolor de cabeza es una razón más excusable para salir de ella en lugar de decir; no quiero. 

2
La mentira: "Voy a pedir una ensalada '
Mentira similar: "Yo no tengo hambre." 

La verdad: "Yo estoy tratando de ser saludable así que voy a pedir algo pequeño - pero eso no significa que no pueda comer en su plato. '

¿Por qué dicen está mentira? Se trata de que quieren estar seguras de molestar a su hombre! ¿Por qué pedir una ensalada y luego comer de tu plato? Es porque les gustaría pensar que son capaces de adherirse a nuestro plan de alimentación y ser saludables, pero cuando ven algo malo - justo en frente de ellas - simplemente no pueden resistir. 

3
La mentira: "No me importa si te fijas en otras mujeres '
Mentiras similares: 'No me pongo celosa. "/ 'Estoy totalmente segura de confiar en ti. "

La verdad: "No me gusta cuando muestras interés en otras mujeres - me daña mi confianza." 

¿Por qué dicen esto mentira? Incluso las mujeres con más confianza tienen una punzada cuando su hombre mira a otra persona. Les gusta fingir que son inmunes y que son comprensivas, pero en el fondo no les gusta.

4
La mentira: "Dime la verdad ... me veo bien en esto? '
Mentiras similares: 'Quiero una opinión sincera.' / 'No voy a enojarme. 

La verdad: 'Tengo que estar tranquila por lo que si no me dices exactamente lo que quiero oír, no voy a ser feliz. "

¿Por qué dicen está mentira? No se puede pedir un cumplido. A veces se sienten un poco inseguras acerca de su apariencia y necesitan un poco de impulso de su ser querido. 

5
La mentira: "No me gustan los días de San Valentín '
Mentiras similares: 'Yo no necesito las flores. "/ 'No tienes que darme nada.' 

La verdad: 'me gusta un poco de romance, pero no quiero forzarlo.' 

¿Por qué dicen esta mentira? No quieren tener que pedirlo! Incluso las mujeres más empedernidas disfrutan de un poco de romance espontáneo del hombre que aman. 

6
La mentira: "No me importa si vemos el fútbol en su lugar '
Mentiras similares: 'No me importa ... si vamos a casa de tu madre para el fin de semana.' / '... Si invitas a tus compañeros a ver el fútbol. "

La verdad: 'Realmente no me gusta, pero yo no voy a decirlo en voz alta. "

¿Por qué dicen esta mentira? A pesar de lo que diga la gente, las mujeres no les gusta dar lata y decir no a algo que él quiere hacer. Sólo esperan que te des cuenta de que no quieren verlo todo el tiempo. 

7
La mentira: "Fue una oferta '
Mentiras similares:-No fue tan caro. "/ "Yo sólo pasamos ..." / "No es nuevo, lo he tenido en mucho tiempo. '

La verdad: "Me pasé más de lo que debería, así que voy a fingir que no sucedió." 

¿Por qué dicen esta mentira? Incluso la mejor de ellas no puede resistir un pequeño derroche de compras de vez en cuando. El problema es que se sienten culpables si se exceden y el odio que muestran esto a nuestro socio y frente a su juicio. Así que es más fácil fingir que era una ganga. 

8
La mentira: "Es lo que siempre he querido" 
Mentiras similares: "La intención es lo que cuenta." / 'No tienes que darme nada.' 

La verdad: "La verdad es que no me gusta esto, pero no quiero herir tus sentimientos." 

¿Por qué dicen esta mentira? Éste es por una buena razón! A menudo mienten y dicen que aman los presentes, ya que prefieren tener un regalo "lindo" que un compañero herido.

9
La mentira: 'Estoy bien' 
Mentiras similares: "No estoy enojada." / 'Usted no me ha trastornado. 

La verdad: "Yo estoy loca, pero no quiero hablar de eso ahora mismo! '

¿Por qué dicen esto mentira? A veces son realmente trastornos. Pero a veces están tan molestas que les da miedo hablar y empeorar las cosas. O, lo que es molesto a ustedes es muy pequeño y nos sentiríamos un poco tontas si nos dijo en voz alta. 

10
La mentira: "Sólo será un minuto '
Mentiras similares: 'Voy a tener un rápido vistazo en la tienda. "/ 'Voy a estar lista en 5 minutos.' 

La verdad: "Yo sé que esto va a tomar mucho más tiempo." 

¿Por qué dicen esta mentira? Saben que no va a gustar la verdad


Por: Alfonso Díaz Navarro

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 .