Sadik Sikder
Sadik Sikder

Reputation: 21

Why am I not getting same output in Ruby

I'm not getting the consistent output in two cases:

Scenario 1:

humen = {"hand" => 1, "eye" => 2, "head" => 3, "hair"=>4}
puts  "enter any body part name"
internal = gets.chomp.downcase.to_s

body = humen[internal]

puts body
#if input is "eye", it comes out 2

Scenario 2:

humen = {hand:1, eye:2, head:3, hair:4}
puts  "enter any body part name"
internal = gets.chomp.downcase.to_s

body = humen[internal]

puts body

I see nothing in irb console. Can anyone please explain why that's the case?

Upvotes: 0

Views: 42

Answers (1)

kiddorails
kiddorails

Reputation: 13014

keys are symbol in second case -

{:hand=>1, :eye=>2, :head=>3, :hair=>4}

whereas internal is a string. humen[internal] is expecting the string assigned to internal to be present in hash humen which is not the case.

:hand != 'hand'

You should convert the string to symbol by:

humen[internal.to_sym]

String#to_sym converts a string into a symbol.

Upvotes: 6

Related Questions