C
cribe
Ok, I have a class that extends array but I'm seeing bizarre behavior when I try to do group_by on it.
# first I thought, maybe it uses object_id
"a".object_id == "a".object_id #=> false
["a", "b", "a"].group_by {|i| i} #=> #<OrderedHash {"a"=>["a", "a"], "b"=>["b"]}>
#ok, that's not it. maybe inspect()?
class Klass
def initialize(v)
@value = v
end
def inspect
@value
end
end
arr = []
(0..10).each do |x|
arr << Klass.new(rand(3))
end
arr.group_by {|i| i} #=> #<OrderedHash {2=>[2], 1=>[1], 0=>[0], 2=>[2], 1=>[1], 1=>[1], 2=>[2], 0=>[0], 2=>[2], 2=>[2], 0=>[0]}>
#nope. and yet:
[2, 1, 0, 2, 1, 1, 2, 0, 2, 2, 0].group_by {|i| i} #=>#<OrderedHash {0=>[0, 0, 0], 1=>[1, 1, 1], 2=>[2, 2, 2, 2, 2]}>
# however, if I explicitly call inspect then it works
arr.group_by {|i| i.inspect} #=> #<OrderedHash {0=>[0, 0, 0], 1=>[1, 1, 1], 2=>[2, 2, 2, 2, 2]}>
Any ideas?
(BTW this was all being done in a rails console which is why the results were returning orderedhashes instead of regular hashes but the results are the same in irb anyway)
# first I thought, maybe it uses object_id
"a".object_id == "a".object_id #=> false
["a", "b", "a"].group_by {|i| i} #=> #<OrderedHash {"a"=>["a", "a"], "b"=>["b"]}>
#ok, that's not it. maybe inspect()?
class Klass
def initialize(v)
@value = v
end
def inspect
@value
end
end
arr = []
(0..10).each do |x|
arr << Klass.new(rand(3))
end
arr.group_by {|i| i} #=> #<OrderedHash {2=>[2], 1=>[1], 0=>[0], 2=>[2], 1=>[1], 1=>[1], 2=>[2], 0=>[0], 2=>[2], 2=>[2], 0=>[0]}>
#nope. and yet:
[2, 1, 0, 2, 1, 1, 2, 0, 2, 2, 0].group_by {|i| i} #=>#<OrderedHash {0=>[0, 0, 0], 1=>[1, 1, 1], 2=>[2, 2, 2, 2, 2]}>
# however, if I explicitly call inspect then it works
arr.group_by {|i| i.inspect} #=> #<OrderedHash {0=>[0, 0, 0], 1=>[1, 1, 1], 2=>[2, 2, 2, 2, 2]}>
Any ideas?
(BTW this was all being done in a rails console which is why the results were returning orderedhashes instead of regular hashes but the results are the same in irb anyway)