Home » Ruby » What is the answer to the bonus question in test_changing_hashes of Ruby Koans?

What is the answer to the bonus question in test_changing_hashes of Ruby Koans?

Posted by: admin November 30, 2017 Leave a comment

Questions:

In the Ruby Koans, the section about_hashes.rb includes the following code and comment:

def test_changing_hashes
    hash = { :one => "uno", :two => "dos" }
    hash[:one] = "eins"

    expected = { :one => "eins", :two => "dos" }
    assert_equal true, expected == hash

    # Bonus Question: Why was "expected" broken out into a variable
    # rather than used as a literal?
end

I can’t figure out the answer to the bonus question in the comment – I tried actually doing the substitution they suggest, and the result is the same. All I can figure out is that it is for readability, but I don’t see general programming advice like that called out elsewhere in this tutorial.

(I know this sounds like something that would already be answered somewhere, but I can’t dig up anything authoritative.)

Answers:

It’s because you can’t use something like this:

assert_equal { :one => "eins", :two => "dos" }, hash

Ruby thinks that { … } is a block. So, you should “broken it out into a variable” but you always can use assert_equal({ :one => "eins", :two => "dos" }, hash)

Questions:
Answers:

I thought it was more readable, but you can still do something like this:

assert_equal true, { :one => "eins", :two => "dos" } == hash

Questions:
Answers:

Another test you can use is the following:

assert_equal hash, {:one => "eins", :two => "dos"}

I’ve simply swapped the parameters to assert_equal.
In this case Ruby will not throw an exception.

But it still seems a bad solution to me. It’s much more readable using a separate variable and testing a boolean condition.