我有一串字母和一串数字:
directions = ur
wieghts = 63 3
我想哈希他们。然后,我希望得到类似的东西:
u is 63
r is 3
我这样做了:
d = Array.new
d.push(directions.split(""))
w = Array.new
w.push(wieghts.split(/\s/))
@h = Hash[d.zip w]
稍后在程序中,我调用包含此zip的类:
f = info[1].gethash
f.each {|key, value| puts " #{key} is #{value}"}
但我明白了:
["u", "r"] is ["63", "3"]
我做错了什么?
答案 0 :(得分:1)
更改如下
d = Array.new
d.push(*directions.split("")) # splat the inner array
w = Array.new
w.push(*weights.split(/\s/)) # splat the inner array
directions.split("")
为您提供了一个数组,您将其推送到d
,而您应该推送由directions.split("")
创建的数组元素。因此,为了满足这一需求,您必须使用 splat运算符(*),就像我在上面*directions.split("")
所做的那样。使用*
时需要使用*weights.split(/\s/)
。
追加 - 将 给定对象 推送到此数组的末尾。
示例:
(arup~>~)$ pry --simple-prompt
>> a = []
=> []
>> b = [1,2]
=> [1, 2]
>> a.push(b)
=> [[1, 2]] # see here when I didn't use splat operator.
>> a.clear
=> []
>> a.push(*b) # see here when I used splat operator.
=> [1, 2]
一个建议,我认为下面就足够了:
d = directions.split("") # d = Array.new is not needed
w = weights.split(/\s/) # w = Array.new is not needed
@h = Hash[d.zip w]
答案 1 :(得分:0)
假设您已正确声明变量:
directions = 'ur'
weights = '63 3'
然后你可以这样做:
Hash[directions.chars.zip(weights.split)]