【问题标题】:zip not producing correct results [closed]zip没有产生正确的结果[关闭]
【发布时间】:2014-03-14 09:31:46
【问题描述】:

我有一串字母和一串数字:

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

我做错了什么?

【问题讨论】:

  • 您的字符串和数字不是有效的 Ruby 对象。你的@h 没用,没用。 info 是什么? gethash 是什么?解释所有变量。

标签: ruby string hash map


【解决方案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 operator(*),就像我在上面的*directions.split("") 中所做的那样。同样的解释也需要使用**weights.split(/\s/)

阅读push(obj, ... ) → ary的文档

Append — 将 给定对象 推到此数组的末尾。

例子:

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

【讨论】:

    【解决方案2】:

    假设你的变量声明正确:

    directions = 'ur'
    weights = '63 3'
    

    那么你可以这样做:

    Hash[directions.chars.zip(weights.split)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 2019-07-04
      相关资源
      最近更新 更多