最有效的红宝石方式来改造这个阵列?

[英]most efficient ruby way to transform this array?


I have an array in the following form:

我有一个以下形式的数组:

  [\"id\", 545, \"program_name\", \"VILLIANS MARATHON\", \"episode_name\", \"1-Season1:Ep.11\"]

I need to transform it to the form below:

我需要将其转换为以下表格:

  [545, \"VILLIANS MARATHON\", \"1-Season1:Ep.11\"]

The way Im doing this is as follows:

我这样做的方式如下:

    #Convert a Active record hash to a 2D array
def activerecord_hash_to_datatable_array(activerecord_resultset)
array_of_arrays = Array.new()
array_of_rs_hashes = activerecord_resultset.to_a.map(&:serializable_hash)

array_of_rs_hashes.each do |rs| 
# {"id"=>1594, "program_name"=>nil, "episode_name"=>nil}
rs =  rs.flatten
#[\"id\", 545, \"program_name\", \"MARATHON\", \"episode_name\", \"1-Season1:Ep.11\"]"
rs_array = Array.new()
index = 1
while index < rs.length     
    puts "index = #{index}"     
    puts "\033[0;33m"+"#{rs[index]}"+"\033[0;37m"
    log_with_yellow("index[#{index}] " + "#{rs[index]}")
    rs_array << rs[index]
    index += 2
end
array_of_arrays <<  rs_array
end
array_of_arrays
end

I was wondering what the most efficient way to accomplish this is.

我想知道实现这一目标的最有效方法是什么。

Clearly I need to retain only odd elements. But Id like to avoid iterating over all elements and comparing each elements index.

显然,我只需保留奇数元素。但我想避免迭代所有元素并比较每个元素索引。

Is there a way to do this by skipping all the even elements ?

有没有办法通过跳过所有偶数元素来做到这一点?

Thanks

谢谢

5 个解决方案

#1


3  

You can do the following:

您可以执行以下操作:

your_array.values_at(*your_array.each_index.select(&:odd?))
=> [545, "VILLIANS MARATHON", "1-Season1:Ep.11"]

#2


2  

require 'json'
arr = JSON.parse("[\"id\", 545, \"program_name\", \"VILLIANS MARATHON\", \"episode_name\", \"1-Season1:Ep.11\"]")
new_arr = arr.select.with_index { |x,i| i.odd? }
p new_arr
# >> [545, "VILLIANS MARATHON", "1-Season1:Ep.11"]

#3


1  

If array_of_rs_hashes is indeed an array of hashes, can't you just do:

如果array_of_rs_hashes确实是一个哈希数组,那么你不能这样做:

res = array_of_rs_hashes.map(&:values)

#4


1  

Yep there is :

是的,有:

require 'json'
Hash[*JSON.parse(s)].values #=> [545, "VILLIANS MARATHON", "1-Season1:Ep.11"] 

where s = "[\"id\", 545, \"program_name\", \"VILLIANS MARATHON\", \"episode_name\", \"1-Season1:Ep.11\"]"

其中s =“[\”id \“,545,\”program_name \“,\”VILLIANS MARATHON \“,\”episode_name \“,\”1-Season1:Ep.11 \“]”

#5


0  

Try:

尝试:

your_2d_array.map {|a| a.each_slice(2).map {|key, value| value}}

If you ahve active support, you can write it slightly more readible:

如果你有积极的支持,你可以写得更加可读:

your_2d_array.map {|a| a.each_slice(2).map(&:second)}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2014/01/15/133135809fa2ef95a716bf2c2defee11.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号