VegaStudios VegaStudios -4 years ago 116
Ruby Question

Why does slice require ! to work?

I am using the

slice
method to create a new object from the attributes of another object.

What I find odd is that, in MiniTest, printing out

user_group.attributes.slice(ArchivedUserGroup.attribute_names)


returns an empty array. However, using
!
("bang") works and returns all of the
user_group
attributes.

Can someone give me some insight into why
slice
works this way?

UserGroup.where(user_id: self.id).each do |user_group|
ArchivedUserGroup.create(
user_group.attributes.slice!(ArchivedUserGroup.attribute_names)
)
end

Answer Source

Hash#slice! returns hash with removed elements while Hash#slice returns selected elements:

{ foo: 1, bar: 2 }.slice(:foo, :bar)
=> {:foo=>1, :bar=>2}
{ foo: 1, bar: 2 }.slice!(:foo, :bar)
=> {}

Also, slice! (with a bang) mutates hash (by removing non-sliced elements), so by conventions, this method has a bang.

It seems like you have not attributes with ArchivedUserGroup.attribute_names keys, so slice! just returns attributes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download