我想以以下格式从散列开始构建一个新数组:
HashConst = {[120,240] => 60, [240,480]=> 30} #Constant
我需要构建一个新数组,并以以下格式将其赋值为新常量:
[ [[120,240] ,1], [[240,480], 1] ]
我试过:
NewArrayConst = HashConst.keys.each{ |res| [res, 1]}
但我却得到了
[ [120,240], [240,480] ]
我找到的唯一解决方案如下:
tempVar = []
HashConst.keys.each_with_index{ |res,idx| tempVar [idx] = [res, 1]}
NewArrayConst = tempVar
任何人都知道更好的解决方案,并且可以解释为什么我不能从NewArrayConst = HashConst.keys.each{ |res| [res, 1]}
获得我期望的输出。我用的是2.2.2-p95
编辑:
正如许多人指出的,哈希变量名称是错误的和误导的,我已经更新了它,以避免混淆。
发布于 2016-01-06 09:41:12
您需要使用map
而不是each
。
Array#each
方法不返回在块中执行的代码的结果,而是返回调用each
的数组,在您的示例中,该数组是hash.keys
的值。
Array#map
将块返回的值收集到数组中。
hash = {[120,240] => 60, [240,480]=> 30}
p array = hash.keys.map{ |res| [res, 1]}
#=> [[[120, 240], 1], [[240, 480], 1]]
注意:不要命名变量Hash
,因为它在Hash
中已经是一个众所周知的类了。如果需要使用小写hash
。此外,对于变量名(如NewArrayConst
),避免使用camel大小写,因为Ruby建议使用snake_case
来命名变量--有关更多细节,您可以参考红宝石风格指南。
发布于 2016-01-06 10:18:30
h = {[120,240] => 60, [240,480]=> 30}
val = 1
h.keys.product([val])
#=> [[[120, 240], 1], [[240, 480], 1]]
发布于 2016-01-06 09:41:29
你试过Hash.to_a
了吗?有时候事情比你想象的容易。
https://stackoverflow.com/questions/34639263
复制