Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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

like image 215
Bruce Avatar asked Sep 23 '11 19:09

Bruce


1 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 it should be "broken out into a variable", but you can always use assert_equal({ :one => "eins", :two => "dos" }, hash)

like image 54
Vasiliy Ermolovich Avatar answered Sep 20 '22 12:09

Vasiliy Ermolovich