0

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
NotAnAmbiTurner
  • 2,553
  • 2
  • 21
  • 44
  • this question is asked before - https://stackoverflow.com/questions/47058364/ruby-koans-step-41-hashes-with btw, `<<` is called shovel operator, you can search by that name. – marmeladze Nov 01 '17 at 15:57
  • @marmeladze The operator itself also does other things like bit shifting, but in this particular context, an array, it does shovel. – tadman Nov 01 '17 at 17:19
  • @tadman i thought it is called shovel because it looks like shovel. do not know if "shoveling" has some other meaning. – marmeladze Nov 01 '17 at 17:57
  • I had no idea this was called shovelling - learning! – NotAnAmbiTurner Nov 02 '17 at 01:01

0 Answers0