在嵌套数组中单独访问对象

时间:2015-12-28 17:44:31

标签: ruby variable-assignment

如何分别访问此哈希中的三个对象?

hash = {"Paul" => [25, 18]}

在此代码中,

hash.each_pair do |k, v|
  print "#{k}: "
  v.each do |n|
    print "#{n} "
  end
  print "\n"
end

变量n作为单个对象访问[25, 18]。举例来说|n, m|不起作用。

2 个答案:

答案 0 :(得分:1)

你可以像下面那样

hash = {}
hash["Paul"] = [25, 18]

hash.each_pair do |k, (v1, v2, *rest)|
    print "#{k}: "
    print "#{v1} "
    print "#{v2} "
    print "\n"
end
#=> Paul: 25 18 

或者,您可以尝试以下内容:

hash = {}
hash["Paul"] = [25, 18]

hash.each_pair do |k, v|
    print "#{k}: "
    v.tap { |m, n| 
        print "#{m} "
        print "#{n} "
    }
    print "\n"
end
#=> Paul: 25 18 

答案 1 :(得分:0)

merge_cells Axlsx::cell_r(0,0) + ':' + Axlsx::cell_r(1,0)
merge_cells Axlsx::cell_r(2,0) + ':' + Axlsx::cell_r(3,0)