← Ruby EspañolChapter 06 of 13

Colecciones

## Objetivos de Aprendizaje - Trabajar con arrays y sus metodos - Dominar hashes y claves de simbolos - Comprender rangos - Usar el modulo Enumerable ## Arrays ### Crear Arrays ```ruby vacio = [] numeros = [1, 2, 3, 4, 5] mixto = [1, "dos", 3.0, nil] anidado = [[1, 2], [3, 4]] # Array.new ceros = Array.new(5, 0) # [0, 0, 0, 0, 0] contados = Array.new(5) { |i| i + 1 } # [1, 2, 3, 4, 5] ``` ### Acceder a Elementos ```ruby frutas = ["manzana", "banana", "cereza", "dato"] puts frutas[0] # "manzana" puts frutas[-1] # "dato" (ultimo elemento) puts frutas[1, 2] # ["banana", "cereza"] (inicio, longitud) puts frutas[0..2] # ["manzana", "banana", "cereza"] (rango) puts frutas.first # "manzana" puts frutas.last # "dato" puts frutas.sample # Elemento aleatorio ``` ### Modificar Arrays ```ruby frutas = ["manzana", "banana"] frutas << "cereza" # Agregar al final frutas.push("dato") # Empujar al final frutas.unshift("albaricoque") # Prepend eliminado = frutas.pop # Eliminar y retornar ultimo primero = frutas.shift # Eliminar y retornar primero frutas.insert(1, "arandano") # Insertar en indice frutas.delete("banana") # Eliminar todas las ocurrencias frutas.delete_at(0) # Eliminar en indice frutas.reverse! frutas.sort! frutas.uniq! # Eliminar duplicados ``` ### Metodos de Arrays ```ruby numeros = [1, 2, 3, 4, 5] numeros.length # 5 numeros.size # 5 numeros.empty? # false numeros.include?(3) # true numeros.join # "12345" numeros.join(", ") # "1, 2, 3, 4, 5" numeros.flatten # Aplanar arrays anidados numeros.compact # Eliminar valores nil numeros.shuffle # Orden aleatorio numeros.rotate # Rotar elementos ``` ### Buscar en Arrays ```ruby numeros = [1, 2, 3, 4, 5, 3] numeros.index(3) # 2 (primer indice) numeros.rindex(3) # 5 (ultimo indice) numeros.find { |n| n > 3 } # 4 numeros.select { |n| n > 3 } # [4, 5] numeros.reject { |n| n > 3 } # [1, 2, 3, 3] numeros.bsearch { |n| n > 3 } # 4 (busqueda binaria) ``` ## Hashes ### Crear Hashes ```ruby vacio = {} usuario = { "nombre" => "Alicia", "edad" => 30 } # Claves de simbolo (preferido) usuario = { nombre: "Alicia", edad: 30 } usuario = { :nombre => "Alicia", :edad => 30 } # Hash.new con valor por defecto conteos = Hash.new(0) conteos[:manzanas] += 1 # {:manzanas => 1} # Forma con bloque valores_por_defecto = Hash.new { |hash, clave| hash[clave] = [] } ``` ### Acceder a Elementos del Hash ```ruby usuario = { nombre: "Alicia", edad: 30, ciudad: "NYC" } puts usuario[:nombre] # "Alicia" puts usuario["nombre"] # nil (tipo de clave diferente) puts usuario[:altura] # nil # Fetch con valor por defecto puts usuario.fetch(:edad, 0) # 30 puts usuario.fetch(:altura, 0) # 0 # Con bloque para clave faltante puts usuario.fetch(:altura) { 0 } # 0 ``` ### Modificar Hashes ```ruby usuario = { nombre: "Alicia", edad: 30 } usuario[:ciudad] = "NYC" # Agregar/actualizar usuario.store(:pais, "USA") usuario.delete(:edad) # Eliminar clave usuario.delete_if { |k, v| v.nil? } usuario.merge!(otro_hash) # Mezclar en lugar ``` ### Metodos de Hash ```ruby usuario = { nombre: "Alicia", edad: 30 } usuario.keys # [:nombre, :edad] usuario.values # ["Alicia", 30] usuario.to_a # [[:nombre, "Alicia"], [:edad, 30]] usuario.has_key?(:nombre) # true usuario.key?(:nombre) # true (alias) usuario.value?("Alicia") # true usuario.has_value?("Alicia") # true usuario.empty? # false usuario.size # 2 ``` ### Iterar sobre Hashes ```ruby usuario = { nombre: "Alicia", edad: 30, ciudad: "NYC" } usuario.each do |clave, valor| puts "#{clave}: #{valor}" end usuario.each_key { |clave| puts clave } usuario.each_value { |valor| puts valor } # Transformar Hash[usuario.map { |k, v| [k, v.to_s] }] ``` ## Rangos ### Crear Rangos ```ruby inclusivo = 1..10 # Incluye el final exclusivo = 1...10 # Excluye el final letras = "a".."z" alfabeto = "a"...("z".ord.chr) rescue "a".."z" ``` ### Metodos de Rangos ```ruby rango = 1..10 rango.to_a # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] rango.include?(5) # true rango.member?(5) # true (alias) rango.cover?(5) # true (mas rapido que include?) (1..5).each { |n| puts n } # Tamano/Longitud (1..10).size # 10 ``` ## Modulo Enumerable Arrays y hashes incluyen Enumerable, proporcionando potentes metodos de iteracion. ### map (collect) ```ruby [1, 2, 3].map { |n| n * 2 } # [2, 4, 6] # Con simbolo ["alice", "bob"].map(&:upcase) # ["ALICE", "BOB"] ``` ### select (find_all) ```ruby [1, 2, 3, 4, 5].select(&:odd?) # [1, 3, 5] [1, 2, 3, 4, 5].find_all { |n| n > 2 } # [3, 4, 5] ``` ### reject ```ruby [1, 2, 3, 4, 5].reject(&:even?) # [1, 3, 5] ``` ### reduce (inject) ```ruby [1, 2, 3, 4, 5].reduce(0) { |suma, n| suma + n } # 15 [1, 2, 3, 4, 5].reduce(:+) # 15 (forma abreviada) # Con valor inicial omitido [1, 2, 3].reduce(:*) # 6 ``` ### find (detect) ```ruby [1, 2, 3, 4, 5].find { |n| n > 2 } # 3 [1, 2, 3, 4, 5].detect { |n| n > 2 } # 3 ``` ### count ```ruby [1, 2, 3, 4, 5].count # 5 [1, 2, 3, 4, 5].count(&:even?) # 2 ``` ### sort y sort_by ```ruby [3, 1, 4, 1, 5, 9, 2, 6].sort # [1, 1, 2, 3, 4, 5, 6, 9] usuarios = [{nombre: "Bob", edad: 30}, {nombre: "Alicia", edad: 25}] usuarios.sort_by { |u| u[:edad] } # Ordenado por edad ``` ### group_by ```ruby [1, 2, 3, 4, 5, 6].group_by(&:odd?) # {true=>[1, 3, 5], false=>[2, 4, 6]} ``` ### partition ```ruby puntajes = [45, 70, 85, 90, 55] aprobados, reprobados = puntajes.partition { |s| s >= 60 } # aprobados = [70, 85, 90] # reprobados = [45, 55] ``` ### zip ```ruby [1, 2, 3].zip([4, 5, 6]) # [[1, 4], [2, 5], [3, 6]] ``` ### take y drop ```ruby [1, 2, 3, 4, 5].take(3) # [1, 2, 3] [1, 2, 3, 4, 5].drop(2) # [3, 4, 5] ``` ## Sets ```ruby require 'set' s1 = Set.new([1, 2, 3]) s2 = Set.new([2, 3, 4]) s1.union(s2) # Set#{1, 2, 3, 4} s1.intersection(s2) # Set#{2, 3} s1.difference(s2) # Set#{1} ``` ## Resumen - Arrays: colecciones ordenadas indexadas por entero - Hashes: pares clave-valor, claves de simbolo preferidas - Rangos: datos secuenciales con `..` (inclusivo) o `...` (exclusivo) - Enumerable: modulo que proporciona potentes metodos de iteracion - `map`: transformar elementos - `select/reject`: filtrar elementos - `reduce`: combinar elementos - `find`: obtener primera coincidencia - `sort_by`: ordenar por propiedad - `group_by`: agrupar por criterio

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →