简体   繁体   中英

How do I extract array values from hashes?

I'm struggling with a data structures in Ruby.

I have:

answers = [
    {"val"=>["6"], "comment"=>["super"], "qid"=>["2"]},
    {"val"=>["3"], "comment"=>[""], "qid"=>["1"]},
    {"val"=>["7"], "comment"=>[""], "qid"=>["4"]},
    {"val"=>["5", "6"], "comment"=>["supera", "hmm"], "qid"=>["1", "2"]},
    {"val"=>["5", "9"], "comment"=>["super", "asdf"], "qid"=>["1", "5"]}
]

I need the following arrays for the qid's, which should be unique, all over the hashes:

["2","1","4","5"] # note, value 2 exists two times and value 1, 3 times 

The corresponding values should be summarized and divided through number of counts:

["12","13","7","9"] will be: ["6","4.3","7","9"] # 12/2 and 13/3

The comments should be summarized as well:

[["super","hmm"],["","supera","super"],[""],["asdf"]]

I'm wondering if it's cool to put it together in an hash?

So far I have:

a = Hash.new(0)
  answers.each.map { |r| r }.each do |variable|
    variable["qid"].each_with_index do |var, index|
        #a[var] << { :count => a[var][:count] += 1 }
        #a[var]["val"] += variable["val"][index]
        #a[var]["comment"] = a[var]["comment"].to_s + "," + variable["comment"][index].to_s
    end   
  end

I'm trying to generate data for Highcharts Demo - Basic bar . The gem is LazyHighCharts

Any Ideas? Suggestions?

Edit:

Maybe I have to explain again the structure: there are questions id's (qid), each of them has a value and a comment, I am trying to calculate the average of the "val" hashes

OK, I think I understand what you're shooting for...

# lets create a hash to store the data
# such that my_data[qid][0] => value sum
#           my_data[qid][1] => number of times qid appeared
#           my_data[qid][2] => comments array

my_data = {}

# go through answers and fill my_data out

answers.each do |h|
    for i in 0...h["qid"].length
        qid = h["qid"][i]

        # awesome ruby syntax that will set my_data[qid] 
        # only if it hasn't already been set using "or-equals" operator
        my_data[qid] ||= [0, 0, []] 

        my_data[qid][0] += h["val"][i].to_i # add value
        my_data[qid][1] += 1                # increment count
        my_data[qid][2] << h["comment"][i]  # add comment
    end
 end

# how to get the data out for qid of "2"

my_data["2"][0].to_f / my_data["2"][1] # => 6
my_data["2"][2]                        # => ["super", "hmm"]

# and we could do this process for any qid, or all qids by iterating over
# my_data. we could even build the arrays in your OP

qids = []
average_values = []
comments = []

my_data.each do |k, v|
    qids << k
    average_values << v[0].to_f / v[1]
    comments << v[2]
end

# qids           => ["2", "1", "4", "5"]
# average_values => [6, 4.3, 7, 9]
# comments       => [["super", hmm"] ["", "supera", "super"], [""], ["asdf"]]

For qid :

result_qid = answers.map{|i| i['qid']}.flatten.uniq!
#["2", "1", "4", "5"]

result_qid = answers.map{|i| i['qid']}.flatten.group_by{|i| i}.map{|i,j| [i,j.length]}
#[["2", 2], ["1", 3], ["4", 1], ["5", 1]]

I can't figure out the logic for corresponding values!

If storing data in Hash is so restricted, you can define a new Class and manage data processing in that Class. I would have something like this:

class AnswerParser
  def intialize(answers)
    #your implementation here
  end

  def qids
    #your implementation here
  end

  def comments
    #your implementation here
  end
  ...

end

#usage
parser = AnswerParser.new(anwsers)
qids = parser.qids
...

With this, you can separate the codes for easier testing and usability.

Hope this helps.

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