Search code examples
arraysrubyaxlsxruby-hash

Ruby RoR get keys and values from hash separately


I have a hash like this:

hash = {"str1"=>5, "str2"=>9, "str3"=> 3}

hash.keys gives as a result ["str1", "str2", "str3"]

hash.values gives as a result [5, 9, 3]

I'm trying to export this to excel with Axlsx using sheet.add_row

sheet.add_row [hash.keys[0], hash.values[0]]  # hash.keys[0] = "str1" and  hash.values[0] = 5
sheet.add_row [hash.keys[1], hash.values[1]]  # hash.keys[1] = "str2" and  hash.values[1] = 9
sheet.add_row [hash.keys[2], hash.values[2]]  # hash.keys[2] = "str3" and  hash.values[2] = 3

In an Excel sheet, this is the result

str

This is simple if the hash is not big but if it's composed of 20 elements or more for example, doing this this way is not pratical at all !! I want to do this for all the elements of the hash in a better way.

sheet.add_row [hash.keys[0], hash.values[0]]  
sheet.add_row [hash.keys[1], hash.values[1]] 
sheet.add_row [hash.keys[2], hash.values[2]] 
........
sheet.add_row [hash.keys[19], hash.values[19]] 

Solution

  • Simply use Hash#each to iterate over each key-value pair:

    hash = {"str1"=>5, "str2"=>9, "str3"=> 3}
    hash.each { |k, v| sheet.add_row [k, v] }