¿Cómo elimino elementos en blanco de una matriz?
Tengo la siguiente matriz
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
Quiero eliminar elementos en blanco de la matriz y quiero el siguiente resultado:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
¿Hay algún método como compact
que lo haga sin bucles?
16 answers
Hay muchas maneras de hacer esto, una es reject
noEmptyCities = cities.reject { |c| c.empty? }
También puede usar reject!
, que modificará cities
en su lugar. Devolverá cities
como su valor de retorno si rechazó algo, o nil
si no se hacen rechazos. Eso puede ser una trampa si no tienes cuidado (gracias a ninja08 por señalar esto en los comentarios).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-10 03:54:38
1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)
=> ["A", "B", "C"]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-15 17:51:59
En mi proyecto utilizo delete
:
cities.delete("")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 21:47:06
Esto es lo que funciona para mí:
[1, "", 2, "hello", nil].reject(&:blank?)
Salida:
[1, 2, "hello"]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-18 15:28:30
Cuando quiero ordenar un array como este uso:
["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]
Esto eliminará todos los elementos en blanco o nil.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-04 12:05:02
Prueba esto:
puts ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-30 00:27:06
Más explícito
cities.delete_if(&:blank?)
Esto eliminará tanto los valores nil
como los valores de cadena vacía (""
).
Por ejemplo:
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal", nil]
cities.delete_if(&:blank?)
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-14 20:18:25
Use reject
:
>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-15 17:42:41
cities.reject! { |c| c.blank? }
La razón por la que desea usar blank?
sobre empty?
es que el espacio en blanco reconoce nil, cadenas vacías y espacios en blanco. Por ejemplo:
cities = ["Kathmandu", "Pokhara", " ", nil, "", "Dharan", "Butwal"].reject { |c| c.blank? }
Todavía volvería:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Y llamando a empty?
en " "
devolverá false
, que probablemente quieras ser true
.
Nota: blank?
solo es accesible a través de Rails, Ruby solo soporta empty?
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-15 17:49:53
Ya hay muchas respuestas pero aquí hay otro enfoque si estás en el mundo de Rails:
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 21:46:27
Aquí hay un enfoque más para lograr esto
Podemos usar presence
con select
cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]
cities.select(&:presence)
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-05 05:48:03
Aquí hay una solución si tiene tipos mixtos en su matriz:
[nil,"some string here","",4,3,2]
Solución:
[nil,"some string here","",4,3,2].compact.reject{|r| r.empty? if r.class == String}
Salida:
=> ["some string here", 4, 3, 2]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-15 17:51:33
Puedes probar esto
cities.reject!(&:empty?)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-05 06:31:54
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? }
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-04 06:00:00
El camino más corto cities.select(&:present?)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-28 22:16:12
Actualizar con un estricto con join
& split
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split
El resultado será:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Tenga en cuenta que: esto no funciona con una ciudad con espacios
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-02 05:03:05