As I understood it, the <<
operator on arrays was essentially the same as push
. I can't seem to find any good docs on <<
(maybe those symbols don't Google well), for whatever reason.
In case you aren't familiar, Ruby Koans is a test-driven teaching tool. You run a command at command prompt, it executes, tests fail, and you learn by making the tests pass. Not much in the way of explanation (but some), and it is pretty darn good for someone with a background in another language to learn Ruby. The lack of explanation, however, has lead me here.
Here is the correct answer to Ruby Koans 41 (of 282):
def test_default_value_is_the_same_object
hash = Hash.new([])
hash[:one] << "uno"
hash[:two] << "dos"
assert_equal ["uno", "dos"], hash[:one]
assert_equal ["uno", "dos"], hash[:two]
assert_equal ["uno", "dos"], hash[:three]
assert_equal true, hash[:one].object_id == hash[:two].object_id
end
What I am trying to figure out is why using "<<" would return an Array
of values when you retrieve any key from hash
, including non-existent ones. I think this Koans is just trying to note that <<
appends to the default value Array of the Hash
and throws away any keys you try to pass in (or in other words, "you probably don't want this"), but I would love someone to tell me if I am right on that and maybe explain a little further.
It is kind of cool that Ruby hashes have a mutable array attached to them as default values. Not sure how useful that is (maybe someone can tell me), but it is cool.