Arrays de arrays em Ruby
2011-11-09 11:39:51
2011-11-09 11:25:12
Autor: Sony Santos
https://gigawiki.com/sony/arrays-de-arrays-em-ruby
Permalink: https://gigawiki.com/2781
categ = dicas, list; linguagem = ruby
1. Agrupando arrays com zip:
a = [:a, :b, :c]
b = [1, 2, 3]
a.zip b                    #=> [[:a, 1], [:b, 2], [:c, 3]]

2. Agrupando arrays com each_slice:
a = ('a'..'f').to_a        #=> ["a", "b", "c", "d", "e", "f"]
a.each_slice(2).to_a       #=> [["a", "b"], ["c", "d"], ["e", "f"]]

3. Usando each_slice para pegar de N em N elementos:
a = ('a'..'f').to_a
a.each_slice(2) { |x,y| puts "#{x} => #{y}" }

4. Desagrupando apenas um nível com flatten:
a = [[:a, 23], [:b, ['um', 'dois']]]
a.flatten(1)               #=> [:a, 23, :b, ["um", "dois"]]
blog comments powered by Disqus