53

我想each_with_object在哈希上使用,但不知道应该如何使用它。这是我所拥有的:

hash = {key1: :value1, key2: :value2}
hash.each_with_object([]) { |k, v, array| array << k }

NoMethodError: undefined method `<<' for nil:NilClass

是否可以each_with_object在哈希上使用?如果是,语法是什么?

4

2 回答 2

114

使用()

hash.each_with_object([]) { |(k, v), array| array << k }
于 2013-08-16T13:47:05.137 回答
-3

我对此有想法。您可以使用

output =[]
Hash.each_with_index do |e, index| 
  // do something with e. E is aray. e have 2 items.
  // First item of e is key.
  // Last item of e is value.
  // index start with 0.
  // using << with output here.
end
于 2018-04-22T16:00:33.440 回答