将哈希转换为数组

时间:2016-02-12 18:36:34

标签: arrays ruby hash

我正在尝试创建一个采用哈希的方法:

OwnerService

作为参数并返回其键值对的数组,如下所示:

{"H"=> 1, "e"=> 1, "l"=> 3, "o"=> 2, "W"=> 1, "r"=> 1, "d"=> 1}

我有以下内容,但它有缺陷:

arr = [["H", 1], ["e", 1], ..., ["d", 1]]

我不应该使用def toCountsArray(counts) arr = [] i = 0 counts.each do |key, value| arr[i].push [key, value] i += 1 end return arr end 方法或任何类型的助手。任何帮助或指导表示赞赏。

6 个答案:

答案 0 :(得分:3)

你基本上就在那里。对to_a的任意限制是奇怪的,因为有很多方法可以有效地实现相同的目标。不过,要修复原来的例子:

array = [ ]
counts.each do |pair|
  array << pair
end

这是做to_a的混乱方式,但它应该有效。你的错误是试图附加到array特定元素,而不是附加到数组本身。

执行此类操作时使用的模式是:

counts = Hash.new(0)

为每个元素创建一个默认值为0的哈希值。这避免了为分配未定义的键而必须做的舞蹈。

还有一些其他方法可以减少这种情况并使其更像Ruby:

def count_chars(string)
  string.chars.each_with_object(Hash.new(0)) do |char, counts|
    case (char)
    when ' '
      # Ignored
    else
      counts[char] += 1
    end
  end
end

each_with_object方法很方便,因为它在遍历每个迭代可以使用的对象时迭代数组。将哈希与默认值相结合的技巧使得这非常整洁。

如果您有一个较长的“忽略”字符列表,请将其表示为数组。然后,string.chars - exclusions可以删除不需要的内容。我在这里使用了case语句来简化添加特殊行为。

答案 1 :(得分:3)

hash = { "H"=> 1, "e"=> 1, "l"=> 3, "o"=> 2, "W"=> 1, "r"=> 1, "d"=> 1 }

p [*hash]
# => [["H", 1], ["e", 1], ["l", 3], ["o", 2], ["W", 1], ["r", 1], ["d", 1]]

答案 2 :(得分:0)

而不是

arr[i].push [key, value]

使用

arr.push [key, value]

因为arr[i]指的是第i个元素

答案 3 :(得分:0)

I would do something like this:

hash = { "H"=> 1, "e"=> 1, "l"=> 3, "o"=> 2, "W"=> 1, "r"=> 1, "d"=> 1 }

hash.each_with_object([]) { |kv, a| a << kv }
#=> [["H",1],["e",1],["l",3],["o",2],["W",1],["r",1],["d",1]]

答案 4 :(得分:0)

你可以这样做:

def to_counts_array(counts)
  counts.map { |k, v| [k, v] }
end

h = { "H"=> 1, "e"=> 1, "l"=> 3, "o"=> 2, "W"=> 1, "r"=> 1, "d"=> 1 }
to_counts_array(h)

虽然我也喜欢@ steenslag的答案。

答案 5 :(得分:0)

另一种方式,只是映射到自我:

x.map &:itself #=> [["H", 1], ["e", 1], ["l", 3], ["o", 2], ["W", 1], ["r", 1], ["d", 1]]