DEV Community

Discussion on: Figuring Out Hashes In Ruby

Collapse
 
dcrow profile image
Yaroslav Barkovskiy

Actually the following code does not work

var = 'a'
alpha = {:var => 1}

alpha[var]
=> 1

Same with

var = 'a'
alpha = {var: 1}

alpha[:var]
=> 1

They actually create a symbol key :var instead of a string key a

alpha.keys
=> [:var]

If you want to use the value from a variable(in this case var), then you should do it like this

var = 'a'
alpha = { var => 1 }

alpha[var]
=> 1

This code also does not work

fav_dogs.each {|dog, number|
     if dog == :not_dogs
         puts number
}

It seems you forgot an end somewhere(twice). Also as a side note {} blocks can be replaced with do...end blocks.

Something like this

fav_dogs.each do |dog, number|
     if dog == :not_dogs
         puts number
     end
end

fav_dogs.each { |dog, number|
     if dog == :not_dogs
         puts number
     end
}