Primera toma de contacto con Ruby

Haciendo un poco de historia, Ruby, es un lenguaje de programación interpretado y Orientado a objetos. Éste fue creado por Yukihiro Matsumoto, y presenta trazas de Perl, Python y SmallTalk.
- Mi Ejemplo:
Fichero xml (rectangles.xml):
<rectangles>
<rectangle width="23" height="45" />
<rectangle width="45" height="75" />
<rectangle width="67" height="90" />
<rectangle width="32" height="56" />
</rectangles>
Programa en Ruby (rectangles.rb):
# Cálculo superfície rectangulos
# @Author : Jordi Coll Corbilla
#-------------------------------------
require "rexml/document"
include REXML
class Rectangulo
def initialize(alto, ancho)
@alto = alto
@ancho = ancho
end
def superficie
puts "Alto #{@alto}, Ancho #{@ancho}, Superficie: " + String(@alto * @ancho)
end
end
#imprimimos el documento completo
doc = Document.new File.new("rectangles.xml")
print doc
print "\n\n"
#realizamos los cálculos
doc = REXML::Document.new File.new('rectangles.xml')
node = doc.elements.to_a("//rectangle")
node.each do |elem|
alto = Integer(elem.attribute("height").value)
ancho = Integer(elem.attribute("width").value)
rec = Rectangulo.new(alto,ancho)
rec.superficie
rec = nil
end
El resultado de la ejecución:
>ruby rectangles.rb
<rectangles>
<rectangle height='45' width='23'/>
<rectangle height='75' width='45'/>
<rectangle height='90' width='67'/>
<rectangle height='56' width='32'/>
</rectangles>
Alto 45, Ancho 23, Superficie: 1035
Alto 75, Ancho 45, Superficie: 3375
Alto 90, Ancho 67, Superficie: 6030
Alto 56, Ancho 32, Superficie: 1792
>Exit code: 0
Como podéis comprobar el script es muy sencillo y por la red podemos encontrar bastantes librerías para hacer el parsing de los xml. En los enlaces de interés hay varios ejemplos. Espero que os sirva de ayuda y a continuar aprendiendo y mejorando!.
- Enlaces de interés:
Parsing XML Ruby.
Comments
Post a Comment