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

Ruby

Ruby Problem Overview


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.)

Ruby Solutions


Solution 1 - Ruby

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

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

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

Solution 2 - Ruby

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

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

Solution 3 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBruceView Question on Stackoverflow
Solution 1 - RubyVasiliy ErmolovichView Answer on Stackoverflow
Solution 2 - RubyMatt KimView Answer on Stackoverflow
Solution 3 - RubyMich DartView Answer on Stackoverflow