Last active
March 25, 2020 22:48
-
-
Save ckozus/a585f00804c544097b29 to your computer and use it in GitHub Desktop.
Ejemplos en Ruby.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
puts "hola mundo".class | |
puts "hola mundo".upcase | |
puts "curso: ruby on rails. nivel básico".size | |
puts 2 + 3 | |
puts 2.+(3) | |
puts 2.send('+', 3) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Cambio autom?tico del tipo de n?mero. | |
num = 8 | |
7.times do | |
print num.class, " ", num, "\n" | |
num *= num | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Distintas representaciones de números. | |
a = 123456 # Fixnum | |
b = 123_456 # Fixnum (underscore ignorado) | |
c = -543 # Fixnum negativo | |
d = 123_456_789_123_345_789 # Bignum | |
e = 0xaabb # Hexadecimal | |
f = 0377 # Octal | |
g = 0b101_010 # Binario | |
puts a, b, c, d, e, f, g |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uno = "uno" | |
dos = 'dos' | |
tres = %{Esta es una cadena más rebuscada, podemos poner "comillas" y 'apostrofes'} | |
# Definiciones usando "here document" | |
cuatro = <<-end_of_string | |
Esta es una cadena | |
en varias lineas | |
end_of_string | |
cinco = <<end_of_string | |
Esta es otra cadena | |
en varias lineas, | |
pero el terminador tiene que | |
estar al comienzo de la linea. | |
end_of_string | |
# Delimitadores variables (no muy comunes) | |
seis = %q/Equivalente a cadena con apostrofes/ | |
siete = %Q!Equivalente a cadena con comillas dobles! | |
puts uno, dos, tres, cuatro, cinco, seis, siete | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Escapado de caracteres | |
puts 'escape using "\\"' # La cadena está "escapada" | |
puts 'That\'s right' # Ahora el apostrofe. | |
puts "Primera linea\nSegunda linea" # Se incluye un caracter de control, el salto de linea. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
puts "Segundos en el día: #{24*60*60}" | |
puts "#{'Ay! ' * 3}" | |
# Las llaves no son necesarias con variables globales, de instancia y de clase | |
$variable = "1" | |
puts "uno => #$variable" | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
str = "Esta es una cadena\n" | |
puts str | |
puts "Longitud:" | |
puts str.size | |
puts "Convertimos en vector utilizando un separador:" | |
puts str.split(' ') | |
puts "Quitamos duplicados contiguos:" | |
puts str.squeeze | |
puts "Slices:" | |
puts str[1..3] | |
puts str[1] | |
puts str[1, 3] | |
puts str[-4, -2] | |
puts "Cadena invertida:" | |
puts str.reverse | |
puts "Reemplazamos 'es' por 'ES':" | |
puts str.gsub("es", "ES") | |
puts "En Mayúsculas:" | |
puts str.upcase | |
puts "En Minúsculas:" | |
puts str.downcase | |
puts "Iniciales en mayúsculas:" | |
puts str.capitalize | |
puts "Añadir contenido en la cadena:" | |
str << "\nAgregamos una segunda linea.\n" | |
puts str | |
puts "Borramos el \\n al final de la cadena:" | |
puts str.chomp |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
s1 = :simbolo | |
s2 = "simbolo" | |
p s1.class | |
p s2.class | |
p s1 == s2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Creación | |
a = [1, 2, 'tres'] | |
puts "Valores iniciales" | |
p a | |
# Agregar elementos | |
a << 4 | |
puts "Despues de agregar el 4" | |
p a | |
# Obtener elementos | |
puts "Primer elemento" | |
p a[0] | |
puts "Del primero al tercero" | |
p a[0..2] | |
puts "Ultimo elemento" | |
p a[-1] | |
puts "Convertir a cadena" | |
p a.join(';') | |
a = %w{uno dos tres cuatro cinco} | |
puts "Un array de cadenas" | |
p a | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Simbolos | |
# Inicializaciones varias | |
h1 = {} | |
h1 = Hash.new | |
h1 = {:uno => 1, :dos => 2, 'tres' => 3, 4 => 4} | |
p h1[:uno] | |
p h1['tres'] | |
p h1['inexistente'] | |
# Inicializacion con valor por defecto para elementos no encontrados | |
h2 = Hash.new(0) | |
p h2['inexistente'] | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rango1 = 1..10 | |
rango2 = 'a'..'z' | |
rango3 = 'casa'..'casz' | |
puts "primer rango" | |
p rango1.to_a | |
puts "segundo rango" | |
p rango2.to_a | |
puts "tercer rango" | |
p rango3.to_a | |
puts "Inclusiones:" | |
p rango1.include?(0) | |
p rango1.include?(5) | |
puts "Mínimo y máximo" | |
p rango1.min | |
p rango1.max | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def saludo | |
puts "hola mundo!" | |
end | |
saludo |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def saludo(mensaje) | |
return mensaje | |
end | |
puts saludo('hola mundo') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
puts saludo('hola mundo') | |
def saludo(mensaje) | |
"el mensaje fue: #{mensaje}" | |
end | |
puts saludo 'hola mundo' | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def saludo(mensaje, opciones) | |
texto = "" | |
texto << '<html>' if opciones[:formato] == :html | |
texto << mensaje | |
texto << '</html>' if opciones[:formato] == :html | |
texto << "repito: #{mensaje}" if opciones[:bis] | |
texto | |
end | |
puts saludo 'mensaje sin formato', {:formato => :text} | |
puts saludo 'mensaje con formato', {:formato => :html} | |
puts saludo 'mensaje con formato', :formato => :html, :bis => true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def saludo(*mensaje) | |
mensaje.each do |msg| | |
puts msg | |
end | |
end | |
saludo 'hola mundo', 'adios mundo cruel', | |
'hola universo', 'bienvenidos al curso de rails' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def alerta(saldo) | |
if saldo < 5000 | |
msg = "su cuenta alcanzó el monto mínimo permitido" | |
else | |
msg = "todo bien" | |
end | |
end | |
puts alerta 10000 | |
puts alerta 4000 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def alerta(valor) | |
msg = valor.to_s | |
msg << " cuenta en rojo!" unless valor > 5000 | |
msg | |
end | |
puts alerta 10000 | |
puts alerta 5000 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
n = 0 | |
while n < 10 | |
n += 1 | |
puts "contador = #{n}" | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for i in 1..10 | |
puts "contador = #{i}" | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
elementos = [1,2,3,4,5,6,7,8,9,10] | |
for elemento in elementos | |
puts "elemento = #{elemento}" | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
elementos = [1,2,3,4,5,6,7,8,9,10] | |
elementos.each do |elemento| | |
puts "elemento = #{elemento}" | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3.times { puts "X" } | |
1.upto(5) { |i| puts i, " " } | |
99.downto(95) { |i| puts i, " " } | |
50.step(80, 5) { |i| puts i, " " } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def saludo(valor) | |
case valor | |
when Fixnum | |
puts "hola soy un Fixnum" | |
when String | |
puts "hola soy un String" | |
when Array | |
puts "hola soy un Array" | |
end | |
end | |
saludo 1000 | |
saludo "Hola" | |
saludo [1,2,3,4] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def mostrar | |
puts "El mensaje ingresado dice " | |
yield | |
puts "fin." | |
end | |
mostrar do | |
puts 'hola' | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"hola mundo, soy Ruby on Rails".split.each_with_index{|palabra, i| puts "#{i}) #{palabra}" } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# all? | |
%w{ ant bear cat}.all? {|word| word.length >= 3} # true | |
%w{ ant bear cat}.all? {|word| word.length >= 4} # false | |
[ nil, true, 99 ].all? # false | |
# any? | |
%w{ ant bear cat}.any? {|word| word.length >= 3} # true | |
%w{ ant bear cat}.any? {|word| word.length >= 4} # true | |
[ nil, true, 99 ].any? # true | |
# map/collect | |
(1..4).map {|i| i*i } # [1, 4, 9, 16] | |
(1..4).map { "cat" } # ["cat", "cat", "cat", "cat"] | |
# detect/find | |
(1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> nil | |
(1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> 35 | |
# find_all/select | |
(1..10).find_all {|i| i % 3 == 0 } #=> [3, 6, 9] | |
# include? | |
(1..10).include?(0) #=> false | |
(1..10).include?(5) #=> true | |
#max/min | |
(1..10).max | |
(1..10).min | |
#sort_by | |
%w{ manzana pera naranja uva }.sort_by {|word| word.length} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Persona | |
def saluda | |
puts "hola a todos" | |
end | |
end | |
a = Persona.new | |
a.saluda |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Persona | |
def nombre=(valor) | |
@nombre = valor | |
end | |
def nombre | |
puts "hola a todos, mi nombre es #@nombre" | |
end | |
end | |
a = Persona.new | |
a.nombre = 'Ruby' | |
a.nombre |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Persona | |
attr_accessor :nombre | |
def saluda | |
puts "hola a todos, mi nombre es #@nombre" | |
end | |
end | |
a = Persona.new | |
a.nombre = 'Ruby' | |
a.saluda |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Persona | |
attr_accessor :nombre | |
attr_reader :telefonos | |
def initialize(mi_nombre) | |
@nombre = mi_nombre | |
@telefonos = [] | |
end | |
def agendar(numero) | |
@telefonos << numero | |
end | |
def saluda | |
puts "hola a todos, mi nombre es #@nombre" | |
end | |
end | |
a = Persona.new('Ruby') | |
a.agendar '0381 - 480 3339' | |
a.agendar '0381 - 480 5500' | |
a.agendar '0381 - 480 2222' | |
a.saluda | |
puts a.telefonos |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Persona | |
attr_accessor :nombre | |
attr_reader :telefonos | |
def initialize(mi_nombre) | |
@nombre = mi_nombre | |
@telefonos = [] | |
end | |
def agendar(numero) | |
@telefonos << numero | |
end | |
def saluda | |
puts "hola a todos, mi nombre es #@nombre" | |
end | |
end | |
class Empleado < Persona | |
def tipo | |
puts self.class | |
end | |
def saluda | |
super | |
puts "soy #{self.class}" | |
end | |
end | |
a = Empleado.new('pepe') | |
a.saluda | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3.times { print "X " } | |
1.upto(5) { |i| print i, " " } | |
99.downto(95) { |i| print i, " " } | |
50.step(80, 5) { |i| print i, " " } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment