最有效的ruby方式来改造这个数组?

时间:2014-01-15 16:27:07

标签: ruby-on-rails ruby arrays loops iteration

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

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

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

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

我这样做的方式如下:

    #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

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

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

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

由于

5 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

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

答案 1 :(得分: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"]

答案 2 :(得分:1)

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

res = array_of_rs_hashes.map(&:values)

答案 3 :(得分:1)

是的,有:

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

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

答案 4 :(得分:0)

尝试:

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

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

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