Ruby RoR分别从hash中获取key和value

Ruby RoR get keys and values from hash separately

我有这样的哈希:

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

hash.keys 结果为 ["str1", "str2", "str3"]

hash.values 结果为 [5, 9, 3]

我正在尝试使用 sheet.add_row

Axlsx 导出到 excel
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

在Excelsheet中,这是结果

如果散列不大,这很简单,但是如果它由 20 个或更多元素组成,例如,这样做根本不实用! 我想以更好的方式对哈希的所有元素执行此操作。

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

只需使用Hash#each遍历每个键值对:

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