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

In Ruby Koans, the about_hashes.rb section contains 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 not understand the answer to the bonus question in the comment - I tried to actually make the replacement that they offer, and the result is the same. All I can understand is that it is intended for readability, but I don’t see general programming tips like those that are called elsewhere in this tutorial.

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

+55
ruby
Sep 23 '11 at 19:13
source share
3 answers

This is because you cannot use something like this:

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

Ruby considers {...} to be a block. So you have to "break it into a variable", but you can always use assert_equal({ :one => "eins", :two => "dos" }, hash)

+81
Sep 23 '11 at 19:32
source share

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

 assert_equal true, { :one => "eins", :two => "dos" } == hash 
+2
Dec 13
source share

Another test you can use is the following:

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

I just changed the parameters to assert_equal . In this case, Ruby will not throw an exception.

But it still seems like a bad decision to me. Its much readability using a separate variable and checking the logical state.

0
Jun 09 '12 at 17:18
source share



All Articles