banditKing
banditKing

Reputation: 9579

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

Upvotes: 0

Views: 91

Answers (5)

aherve
aherve

Reputation: 4060

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

Upvotes: 1

steenslag
steenslag

Reputation: 80065

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

res = array_of_rs_hashes.map(&:values)

Upvotes: 1

BroiSatse
BroiSatse

Reputation: 44675

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

Upvotes: 0

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

You can do the following:

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

Upvotes: 3

bjhaid
bjhaid

Reputation: 9752

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

Upvotes: 2

Related Questions