-8

我有以下代码:

class A 
end

class B 
end

a1 = A.new
a2 = A.new
b1 = B.new
b2 = B.new

array = [a1, a2, b1, b2]
hash = {}

array.each do |obj|
    if hash[obj.class] = nil
        hash[obj.class] = []
    else
        hash[obj.class] << obj
    end
end

我希望哈希等于

{ A => [a1,a2], B => [b1,b2] }

但它告诉我我不能使用<<运算符。

4

2 回答 2

2

让我们总结一下。

if hash[obj.class] = nil

↑ 每次条件运行时,您都在重置您的配对,因为设置为唯一的相等hash[obj.class]nil不是测试它的无效性。改为使用==
然后,你在做

array.each do |obj|
  if hash[obj.class] == nil
    hash[obj.class] = []    # if nil, initialize to new array
  else                      # but because of the else, you are not...
    hash[obj.class] << obj  # doing this so you don't register the first object of each class.
  end
end

结论

array.each do |obj|
  hash[obj.class] ||= [] # set hash[obj.class] to [] if nil (or false)
  hash[obj.class] << obj
end
于 2013-07-09T02:48:02.677 回答
1

我认为Enumerable#group_by这是您正在寻找的:

# ...

array = [a1, a2, b1, b2]
hash = array.group_by(&:class)
# => {A=>[#<A:0x0000000190dbb0>, #<A:0x000000018fa470>],
#     B=>[#<B:0x000000018e5fe8>, #<B:0x000000018daa80>]}

(正如评论中所指出的,您得到的错误是因为您设置hash[obj.class]nil当您打算测试与 的相等性时==。)

于 2013-07-09T01:31:22.970 回答