Forma correcta de rellenar una matriz con un rango en Ruby
Estoy trabajando en un libro que da ejemplos de Rangos que se convierten en matrices equivalentes utilizando sus métodos "to_a"
Cuando corro el código en irb recibo la siguiente advertencia
warning: default `to_a' will be obsolete
¿Cuál es la alternativa correcta a usar to_a?
¿Hay formas alternativas de rellenar un array con un Rango?
6 answers
Puede crear una matriz con un rango usando splat,
>> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Utilizando Kernel
Array
método,
Array (1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
O usando to_a
(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
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-24 10:56:08
Esto funciona para mí en irb:
irb> (1..4).to_a
=> [1, 2, 3, 4]
Noto que:
irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
from (irb):1
Así que tal vez te estás perdiendo los paréntesis?
(Estoy ejecutando Ruby 1.8.6 patchlevel 114)
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
2008-10-10 13:49:55
Parece que estás haciendo esto:
0..10.to_a
La advertencia es de Fixnum # to_a, no de Range # to_a. Prueba esto:
(0..10).to_a
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-01-19 11:43:49
Comprueba esto:
a = [*(1..10), :top, *10.downto( 1 )]
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-06-12 04:25:55
Acabo de intentar usar rangos de mayor a menor cantidad y obtuve el resultado que no esperaba:
irb(main):007:0> Array(1..5)
=> [1, 2, 3, 4, 5]
irb(main):008:0> Array(5..1)
=> []
Eso se debe a las implementaciones de rangos.
Así que tuve que usar la siguiente opción:
(1..5).to_a.reverse
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-05-20 12:09:11
Esta es otra manera:
Irb > [*1..10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
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-02-27 13:19:52