15. Hashes


#1

Hi,

Below is my code, using literal notation, for "15. Hashes" (http://bit.ly/1Sw0bf9):

1 my_hash = {"collar" => 30,
2 "leash" => 35,
3 "harness" => 50
4 }
5 my_hash.each do |item, price|
6 puts "#{item}: #{price}"
7 end

Result:
collar: 30
leash: 35
harness: 50
{"collar"=>30, "leash"=>35, "harness"=>50}

Could someone please help me achieve the same result using Hash.new? I'm not sure how to start….

Thanks!


#2

@ecchan13,
You could read
http://docs.ruby-lang.org/en/2.0.0/Hash.html
or
http://docs.ruby-lang.org/en/2.1.0/Hash.html

and use a google-search
if you want to have a look at
== discussions / opinions ==
ruby creating a hash using hash.new site:stackoverflow.com


#3

Hi leonhard.wettengmx.n,

Thanks for the links! This code seems to have worked, but would you do anything different?

my_hash = Hash.new
my_hash["collar"] = 30
my_hash["leash"] = 35
my_hash["harness"] = 50

my_hash.each do |item, price|
puts "#{item}: #{price}"
end

Regards,
Ecchan13


#4

Why is my code not working

var hash_name = {"turkey" => 0.66,
"cheese" => 0.50,
"bread" => 0.75
}

My Error is : Oops, try again. Did you declare a variable called my_hash?


#5

@celestia123,
Try it by using

my_hash = {"turkey" => 0.66,
 "cheese" => 0.50,
 "bread" => 0.75
}

Have a look at the documentation
local and global variables
http://docs.ruby-lang.org/en/2.1.0/syntax/assignment_rdoc.html