简体   繁体   中英

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

You can do the following:

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

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

res = array_of_rs_hashes.map(&:values)

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\\"]"

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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM